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
  • 97,193
  • 102
  • 206
  • 364
linus72982
  • 1,418
  • 2
  • 16
  • 31

6 Answers6

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

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

echo $allMessageID_implode;
naveenos
  • 408
  • 1
  • 4
  • 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
  • 7
  • 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
  • 155,785
  • 88
  • 678
  • 743
  • 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
  • 21,021
  • 11
  • 61
  • 82
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
  • 20,761
  • 42
  • 119
  • 178