在数组内循环数组,并在php

时间:2019-02-14 05:19:24

标签: php

我有一个以下格式的数组。

array (
0 => 
array (
'safe_route' => 'yes',
'route_name' => 'route_1',
'route_risk_score' => '2.5'),
 1 =>
array (
'safe_route' => 'no',
'route_name' => 'route_2',
'route_risk_score' => '3.5'),
 2 =>
array (
'safe_route' => 'no',
'route_name' => 'route_3',
'route_risk_score' => '4.5')
)

我需要循环它,并在所有数组中删除键'route_risk_score'及其值。如何做到这一点在PHP中。是php的新手,将不胜感激

2 个答案:

答案 0 :(得分:8)

要删除原始数组中的元素,请对每个元素使用引用

// see this & in front of `$item`? 
// It means that `$item` is a reference to element in original array 
// and unset will remove key in element of original array, not in copy
foreach($array as &$item) {          
    unset($item['route_risk_score']);
}

答案 1 :(得分:6)

$data = array(
0 =>array(
    'safe_route' => 'yes',
    'route_name' => 'route_1',
    'route_risk_score' => '2.5'),
1 =>array(
    'safe_route' => 'no',
    'route_name' => 'route_2',
    'route_risk_score' => '3.5'),
2 =>array(
    'safe_route' => 'no',
    'route_name' => 'route_3',
    'route_risk_score' => '4.5')
);
$count = count($data);
for ($i = 0; $i < count($data); $i++) {
     unset($data[$i]['route_risk_score']);
}
echo'<pre>';print_r($data);die;
output :
Array
(
[0] => Array
    (
        [safe_route] => yes
        [route_name] => route_1
    )

[1] => Array
    (
        [safe_route] => no
        [route_name] => route_2
    )

[2] => Array
    (
        [safe_route] => no
        [route_name] => route_3
    )

)