我有阵列:
$array = Array(
[0] => Array(
[Branch] => 'Toyota',
[Country] => 'Jpn',
[id] => 'jp01'
)
[1] => Array(
[Branch] => 'Nissan',
[Country] => 'Jpn',
[id] => 'jp05'
)
[2] => Array(
[Branch] => 'Honda',
[Country] => 'Jpn',
[id] => 'jp20'
) )
我想做的是:
1 - 将密钥 Branch
更改为 Brand
,但不将其移至最后或数组。
2 - 将所有值更新为关键国家/地区,将 Jpn
更改为 Japan
结果应该是这样的:
$array = Array(
[0] => Array(
[Brand] => 'Toyota',
[Country] => 'Japan',
[id] => 'jp01'
)
[1] => Array(
[Brand] => 'Nissan',
[Country] => 'Japan',
[id] => 'jp05'
)
[2] => Array(
[Brand] => 'Honda',
[Country] => 'Japan',
[id] => 'jp20'
) )
我非常感谢你的帮助。
答案 0 :(得分:3)
$newArray = array();
foreach($array as $ar){
$newArray[] = array(
'Brand' => $ar['Branch'],
'Country' => 'Japan',
'id' => $ar['id']
)
}
$array = $newArray;
答案 1 :(得分:1)
foreach($array as &$item) {
$branch = $item['Branch'];
array_unshift($item, array("Brand"=>$branch));
unset($item['Branch']);
$item['Country'] = 'Japan';
}
没有测试过..
答案 2 :(得分:0)
TRY:
<?php
foreach($array as $key => $data)
{
$data['Brand'] = $data['Branch'];
$data['Country'] = 'Japan';
unset($data['Branch']);
$array[$key] = $data;
}
?>
答案 3 :(得分:0)
这应该这样做。
<?php
foreach($array as $k => $v) {
$array[$k]['Brand'] = $array[$k]['Branch'];
unset($array[$k]['Branch'];
if($array[$k]['Country'] == 'Jpn') {
$array[$k]['Country'] = 'Japan';
}
}
?>
可能也有聪明的数组函数可以做到,但这将完成工作。
答案 4 :(得分:0)
foreach($array as $key => $subArray){
foreach($subArray as $subkey => $value)
if($value === 'Jpn') $subArray[$subkey] = 'Japan';
$array[$key] = $subArray;
}
foreach($array as $key => $subArray){
$subArray = array_flip($subArray);
foreach($subArray as $subkey => $value)
if($value === 'Branch') $subArray[$subkey] = 'Brand';
$subArray = array_flip($subArray);
$array[$key] = $subArray;
}
输出:
Array ( [0] => Array ( [Brand] => Toyota [Country] => Japan [id] => jp01 ) [1] => Array ( [Brand] => Nissan [Country] => Japan [id] => jp05 ) [2] => Array ( [Brand] => Honda [Country] => Japan [id] => jp20 ) )