I have the array:
$array = Array(
[0] => Array(
[Branch] => 'Toyota',
[Country] => 'Jpn',
[id] => 'jp01'
)
[1] => Array(
[Branch] => 'Nissan',
[Country] => 'Jpn',
[id] => 'jp05'
)
[2] => Array(
[Branch] => 'Honda',
开发者_如何学Go [Country] => 'Jpn',
[id] => 'jp20'
) )
What I want to do is:
1 - Change the keyBranch
to Brand
, but without moving it to the end or the array.
2 - Update all the values to the key Country, changing Jpn
to Japan
The result should be like this:
$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'
) )
I really appreciate your help.
$newArray = array();
foreach($array as $ar){
$newArray[] = array(
'Brand' => $ar['Branch'],
'Country' => 'Japan',
'id' => $ar['id']
)
}
$array = $newArray;
foreach($array as &$item) {
$branch = $item['Branch'];
array_unshift($item, array("Brand"=>$branch));
unset($item['Branch']);
$item['Country'] = 'Japan';
}
Haven't tested it..
This should do it.
<?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';
}
}
?>
There are probably clever array functions that could do it, too, but this will get the job done.
TRY:
<?php
foreach($array as $key => $data)
{
$data['Brand'] = $data['Branch'];
$data['Country'] = 'Japan';
unset($data['Branch']);
$array[$key] = $data;
}
?>
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;
}
Outputs:
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 ) )
精彩评论