php - 从关联数组中提取一维数组

时间:2012-10-05 11:32:26

标签: php arrays associative

我有一个如下数组,我希望在一个单独的数组中得到'id'前面的所有值。喜欢: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)

5 个答案:

答案 0 :(得分:5)

您可以使用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);

输出

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

答案 1 :(得分:2)

使用foreach循环并将id放在另一个数组中:

$newArray = array()
foreach($array as $val){
    $newArray[] = $val['id'];
}

答案 2 :(得分:1)

试试这个:

foreach($YourArray as $ar)
{
    $FinalArray[] = $ar['id'];
}

print_r($FinalArray);

答案 3 :(得分:0)

foreach($array as $key=>$value)
{
if(array_key_exists('id',$value))
$arr2[]=$value['id'];
}

答案 4 :(得分:0)

自PHP 5.5起,您可以使用array_column

$idArray = array_column($multiArray, 'id');