mohsen ny mohsen ny - 28 days ago 5
PHP Question

php - extract a 1-dimension array out of an associative array

I have an array as below and I want to get all the values in front of 'id', in a seperated array. Like: arry('12', '10', '11', '9')

array
3 =>
array
'occurance' => int 4
'id' => string '12' (length=2)
1 =>
array
'occurance' => int 3
'id' => string '10' (length=2)
2 =>
array
'occurance' => int 2
'id' => string '11' (length=2)
0 =>
array
'occurance' => int 1
'id' => string '9' (length=1)

Answer

You can use array_map

$values = array(
        3 => array('occurance' => 4,'id' => '12'),
        1 => array('occurance' => 3,'id' => '10'),
        2 => array('occurance' => 2,'id' => '11'),
        0 => array('occurance' => 1,'id' => '9'));

$values = array_map(function($var){ return $var['id']; }, $values);
var_dump($values);

Output

array
  3 => string '12' (length=2)
  1 => string '10' (length=2)
  2 => string '11' (length=2)
  0 => string '9' (length=1)