How to use implode on an array of stdClass objects?

对着背影说爱祢 提交于 2019-12-04 00:53:32

You could use array_map() and implode()...

$a = array_map(function($obj) { return $obj->foo; }, 
               array(1=>$obj1 , 2=>$obj2 , 3=>$obj3));

$a = implode(", ", $a);

This is actually the best way I've found, it doesn't seem to be answered here properly as the array of objects should be able to handle dynamic size.

$str = implode(',', array_map(function($x) { return $x->foo; }, $a));

This also seems to be the cleanest solution I've seen.

osteel

You can actually set __toString() on the class as suggested by Ray, but you don't need to iterate through the array first. implode() will directly call the __toString() function of the objects (which also works with associative arrays, btw).

A very neat solution for this is the array_reduce() function, that reduces an array to a single value:

$str = array_reduce($a, function($v, $w) {
    if ($v) $v .= ',';
    return $v . $w->foo;
});

With PHP 7.0+ you can use array_column for this.

echo implode(',', array_column($a, 'foo'));
Jason
echo implode("','",(array)$data->stdArray);

I guess the easiest way would be to create an ID indexed array and then call implode on array_keys:

$a = array();
$a[4] = stdClass Object ( [foo] => 4 [bar] => 8 [foo-bar] => 15 );
$a[16] = stdClass Object ( [foo] => 16 [bar] => 23 [foo-bar] => 42 );
$a[76] = stdClass Object ( [foo] => 76 [bar] => 79 [foo-bar] => 83 );

echo implode(', ', array_keys($a));

No, the best you can do is iterate through, call tostring() on the object and put the results in a new array to call implode on.

If it's a 1-level object, this worked for me.

function implodeObjValues($glue, $obj) { 
    $s = "";
    foreach($obj[1] as $n=>$v) {
        $s .= $glue . $v;
    }
    return substr($s,strlen($glue));
}

function implodeObjLabels($glue, $obj) { 
    $s = "";
    foreach($obj[1] as $n=>$v) {
        $s .= $glue . $n;
    }
    return substr($s,strlen($glue));
}

Could include a by-type multi-level process, but I didn't need that yet. Hope this helps.

Handy for converting MySQL object back to array.

$db = new mysqli("localhost",$usr,$pw,$db);
$row = $db->query("SHOW TABLES");
$a = implodeObjValues("|",$row);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!