PHP Combining arrays with std class
This is what I want but cant figure out how to.
$a is this array PHP Code:
Array
(
[0] => stdClass Object
(
[id] => i1
[cat] => Test1
)
[1] => stdClass Object
(
[id] => i2
[cat] => Test2
)
[2] => stdClass Object
(
[id] => i3
[cat] => Test3
)
[3] => stdClass Object
(
[id] => i4
[cat] => Test4
)
}
This is the array and it has those std classes associated with it. What I am trying to do is to combine all the "cat" names into one array variable.
开发者_运维问答I want to make $categories an array with all these "cat" as the array values.
How can I do that ?
array_map($a, function(stdClass $o) { return $o->cat; });
A simple way is just to loop over the array, grabbing the values that you want. There are other, fancier ways of doing the same but I like to keep it simple.
$categories = array();
foreach ($a as $obj) {
$categories[] = $obj->cat;
}
Of course, if not all of the array items are that object then it might be worthwhile to check that the cat
property exists (and that $obj
is a stdClass
!).
Simply loop through and create a new array...
<?php
$newArray = array();
foreach($a as $cat) {
$newArray[$cat->id] = $cat->cat;
}
var_dump($newArray);
精彩评论