tags:

views:

207

answers:

4

Hi,

I've got an array of cats objects:

$cats = Array
    (
        [0] => stdClass Object
            (
                [id] => 15
            ),
        [1] => stdClass Object
            (
                [id] => 18
            ),
        [2] => stdClass Object
            (
                [id] => 23
            )
)

and I want to extract an array of cats' IDs in 1 line (not a function nor a loop).

I was thinking about using array_walk with create_function but I don't know how to do it.

Any idea?

+3  A: 
function extract_ids($cats){
    $res = array();
    foreach($cats as $k=>$v) {
        $res[]= $v->id;
    }
    return $res
}

and use it in one line:

$ids = extract_ids($cats);
SilentGhost
Thanks SilentGhost, but my question is about to get $res in only 1 command, not using a loop...
abernier
but why ?
SilentGhost
What difference does it make? This is about as straight-forward as it gets. You'll probably use more lines using something like `array_walk`.
deceze
+9  A: 

You can use the array_map() function.
This should do it:

$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);
Greg
this is the correct solution and will lead to the fact that every upcoming maintainer will be "wtf"'d :D
Andreas Klinger
it is also not scalable. I've no idea why would OP want this approach.
SilentGhost
Exactly what I was looking for but didn't know how to write it! :)Thanks a lot Greg
abernier
The only thing that I dislike about this solution is the use of create_function.
Ionuț G. Stan
You could use a lambda function but not many people will be running PHP 5.3
Greg
+1  A: 

Builtin loops in PHP are faster then interpreted loops, so it actually makes sense to make this one a one-liner:

$result = array();
array_walk($cats, create_function('$value, $key, &$result', '$result[] = $value->id;'), $result)
soulmerge
A: 

CODE

<?php

# setup test array.
$cats = array();
$cats[] = (object) array('id' => 15);
$cats[] = (object) array('id' => 18);
$cats[] = (object) array('id' => 23);

function extract_ids($array = array())
{
    $ids = array();
    foreach ($array as $object) {
        $ids[] = $object->id;
    }
    return $ids;
}

$cat_ids = extract_ids($cats);
var_dump($cats);
var_dump($cat_ids);

?>

OUTPUT

# var_dump($cats);
array(3) {
  [0]=>
  object(stdClass)#1 (1) {
    ["id"]=>
    int(15)
  }
  [1]=>
  object(stdClass)#2 (1) {
    ["id"]=>
    int(18)
  }
  [2]=>
  object(stdClass)#3 (1) {
    ["id"]=>
    int(23)
  }
}

# var_dump($cat_ids);
array(3) {
  [0]=>
  int(15)
  [1]=>
  int(18)
  [2]=>
  int(23)
}

I know its using a loop, but it's the simplest way to do it! And using a function it still ends up on a single line.

Luke Antins