如何将阵列升级?

时间:2014-03-18 10:46:01

标签: php arrays

我有一个像

这样的多维数组
$array ( 
     [1]( [camera_name] = name1 )
     [2]( [camera_name] = name2 )
     [3]( [camera_name] = name3 )
     [4]( [camera_name] = name4 )
)

我只想要它以便

Array (
    [1] = name1,
    [2] = name2,
    [3] = name3,
    [4] = name4 )

我已经尝试了

for($i;$i<count($array);$i++){
     $newArray = $array[$i][camera_name];
}

foreach($array as $key => $value){
     $newArray[$key] = $array[$key][camera_name];
}

但无论我做什么,阵列总是一样:

$newArray ( 
     [1]( [camera_name] = name1 )
     [2]( [camera_name] = name2 )
     [3]( [camera_name] = name3 )
     [4]( [camera_name] = name4 )
)

4 个答案:

答案 0 :(得分:1)

$array = array_map(function (array $item) { return $item['camera_name']; }, $array);

从PHP 5.5开始:

$array = array_column($array, 'camera_name');

答案 1 :(得分:0)

试试这个..

$newArray = array();
$i =1;
foreach($array as $key => $value){
     $newArray[$i] = $value;
     $i++;
}


print_r($newArray);

答案 2 :(得分:0)

只需执行以下代码:

$array    = array( /* added data */ );// your original array
$tempArray = array();

foreach ($array as $key => $value) {
  $tempArray[$key] = $value['camera_name'];
}

print_r($tempArray);

输出不是

$newArray ( 
     [1]( [camera_name] = name1 )
     [2]( [camera_name] = name2 )
     [3]( [camera_name] = name3 )
     [4]( [camera_name] = name4 )
)

答案 3 :(得分:0)

你做错了

应该是这样的:

foreach($array as $key => $value){
    $newArray[$key] = $value['camera_man']; // $value['camera_man']
}

<强>输出:

Array
(
    [1] => name1
    [2] => name2
    [3] => name3
    [4] => name4
)