views:

1796

answers:

5

Say for example you just queried a database and you recieved this 2D array.

$results = array(
    array('id' => 1, 'name' => 'red'  , 'spin' =>  1),
    array('id' => 2, 'name' => 'green', 'spin' => -1),
    array('id' => 3, 'name' => 'blue' , 'spin' => .5)
);

I often find myself writing loops like this.

foreach($results as $result)
    $names[] = $result['name'];

My questions is does there exist a way to get this array $names without using a loop? Using callback functions count as using a loop.

Here is a more generic example of getting every field.

foreach($results as $result)
    foreach($result as $key => $value)
        $fields[$key][] = $value;
+4  A: 

Simply put, no.

You will need to use a loop or a callback function like array_walk.

Devon
A: 

I'm afraid there's no built-in function for this sort of thing. You have to find your quarks' names yourself.

Lucas Oman
+1  A: 

I voted @Devon's response up because there really isn't a way to do what you're asking with a built-in function. The best you can do is write your own:

function array_column($array, $column)
{
    foreach ($array as $row) $ret[] = $row[$column];
    return $ret;
}
inxilpro
A: 

I think this will do what you want

array_uintersect_uassoc

You would have to do something like this

$results = array(
    array('id' => 1, 'name' => 'red'  , 'spin' =>  1),
    array('id' => 2, 'name' => 'green', 'spin' => -1),
    array('id' => 3, 'name' => 'blue' , 'spin' => .5)
);
$name = array_uintersect_uassoc( $results, array('name' => 'value')  , 0, "cmpKey");
print_r($name);

//////////////////////////////////////////////////
// FUNCTIONS
//////////////////////////////////////////////////
function cmpKey($key1, $key2) {
  if ($key1 == $key2) {
    return 0;
  } else {
    return -1;
  }
}

However, I don't have access to PHP5 so I haven't tested this.

Bill
This did not work for me in PHP5. I got a Not a valid callback warning and an empty array.
Devon
It's failing because you have to pass a function not 0. Even if i pass a function that always returns true or false to this i still don't get a valid answer. You can't use array intersect because it's an array inside of an array. You can use array_walk or array_map depending on return type.
gradbot
A: 

I did more research on this and found that ruby and prototype both have a function that does this called array_pluck,2. It's interesting that array_map has a second use that allows you to do the inverse of what i want to do here. I also found a PHP class someone is writing to emulate prototypes manipulation of arrays.

I'm going to do some more digging around and if I don't find anything else I'll work on a patch to submit to the [email protected] mailing list and see if they will add array_pluck.

gradbot