5

Is there a way to implode the values of similar objects contained in an array? I have an array of objects:

$this->inObjs

and I'd like a comma separated string of each of their messageID properties:

$this->inObjs[$i]->messageID

Is there an elegant way to do this or am I going to have to MacGyver a solution with get_object_vars or foreachs or something similar? Thanks for the help.

Soner Gönül
  • 94,086
  • 102
  • 195
  • 339
linus72982
  • 1,388
  • 1
  • 14
  • 27

6 Answers6

4
$allMessageID = '';
foreach ($this->inObjs as $objectDetail) :
    $allMessageID[] = $objectDetail->messageID;
endforeach;

$allMessageID_implode = implode(",", $allMessageID);

echo $allMessageID_implode;
naveenos
  • 398
  • 1
  • 3
  • 7
3

If you can modify the class, you can implement __toString:

class MyObject {
    private $messageID = 'Hello';
    public function __toString() {
        return $this->messageID;
    }
}
// ...
$objectList = array(new MyObject, new MyObject);
echo implode(',', $objectList);
// Output: Hello,Hello
Flori
  • 671
  • 6
  • 12
2

The easiest way that I found is using array_map

$messageIDs = array_map( function($yourObject) { return $yourObject->messageID; }, $this->inObjs );
$string = implode(", ", $messageIDs );
mgreca
  • 86
  • 8
1

Here is a two liner:

array_walk($result, create_function('&$v', '$v = $v->property;'));
$result = implode(',', $result);

Or:

array_walk($result, function(&$v, &$k) use (&$result) { $v = $v->name; } );
$result = implode(',', $result);

Where $v->property is your object property name to implode.

Also see array_map().

kenorb
  • 137,499
  • 74
  • 643
  • 694
  • Why am I seeing `, &$k` and `use (&$result)` here? Please revisit this post. I want to use this page to close another. – mickmackusa Sep 13 '20 at 02:23
1
$messageIDArray;
foreach($this->inObjs as $obj){
   $messageIDArray[] = $obj->messageID;
}

$string = implode(',',$messageIDArray);
Headshota
  • 20,343
  • 11
  • 58
  • 79
1

I usually make a Helper for this situation, and use it like this


function GetProperties(array $arrOfObjects, $objectName) {
     $arrProperties = array();
     foreach ($arrOfObjects as $obj) {
         if ($obj->$objectName) {
              $arrProperties[] = $obj->$objectName;
         }
     }
     return $arrProperties;
}

johnlemon
  • 19,827
  • 38
  • 117
  • 176