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.

0

6 Answers 6

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

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

echo $allMessageID_implode;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

The easiest way that I found is using array_map

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

Comments

1
$messageIDArray;
foreach($this->inObjs as $obj){
   $messageIDArray[] = $obj->messageID;
}

$string = implode(',',$messageIDArray);

3 Comments

he said he knows about foreach
I did not know what solution he did find, so I wrote mine. just a word foreach doesn't mean anything to me...
the first line should be $messageIDArray = [];
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;
}

Comments

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().

1 Comment

Why am I seeing , &$k and use (&$result) here? Please revisit this post. I want to use this page to close another.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.