views:

63

answers:

3

Hello,

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 ?

A: 

Simply loop through and create a new array...

<?php
$newArray = array();

foreach($a as $cat) {
  $newArray[$cat->id] = $cat->cat;
}

var_dump($newArray);
Andrew Moore
+3  A: 
array_map($a, function(stdClass $o) { return $o->cat; });
Artefacto
$categories = array_map( ... );
ebynum
Side note: Anonymous functions like `function(stdClass $o) {...}` are not available in php versions prior to 5.3. see http://docs.php.net/closures
VolkerK
A: 

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

salathe