I am trying to uniformly rename all of my array keys using a foreach loop and unset.
Array before:
Array
( [0] => Array (
[store_nl] => Store One
[id_nl] => 123456
[title_nl] => Product One
[price_nl] => $9.00 )
[1] => Array (
[store_ds] => Store Two
[id_ds] => 789012
[title_ds] => Product Two
[price_ds] => $8.00 )
)
foreach using unset:
if(isset($data)){
foreach ( $data as $k=>$v )
{
//Store One (ds)
$data[$k]['Store'] = $data[$k]['store_ds'];
$data[$k]['ItemID'] = $data[$k]['id_ds'];
$data[$k]['Description'] = $data[$k]['title_ds'];
$data[$k]['Price'] = $data[$k]['price_ds'];
unset($data[$k]['store_ds']);
unset($data[$k]['id_ds']);
unset($data[$k]['title_ds']);
unset($data[$k]['price_ds']);
//Store Two (nl)
$data[$k]['Store'] = $data[$k]['store_nl'];
$data[$k]['ItemID'] = $data[$k]['id_nl'];
$data[$k]['Description'] = $data[$k]['title_nl'];
$data[$k]['Price'] = $data[$k]['price_nl'];
unset($data[$k]['store_nl']);
unset($data[$k]['id_nl']);
unset($data[$k]['title_nl']);
unset($data[$k]['price_nl']);
}
}
Array after:
Array
( [0] => Array (
[Store] => Store One
[ItemID] => 123456
[Description] => Product One
[Price] => $9.00 )
[1] => Array (
[Store] =>
[ItemID] =>
[Description] =>
[Price] => )
)
All of the array keys have been changed, but some of the data is now gone? Can someone please tell me a better way to do this without data loss?
The following will do what you deed:
$myArray = array(
array(
'store_ni' => 'Store One',
'id_ni' => 123456,
'title_ni' => 'Product One',
'price_ni' => '$9.00'
),
array(
'store_ds' => 'Store Two',
'id_ds' => 789012,
'title_ds' => 'Product Two',
'price_ds' => '$8.00'
)
);
$newKeys = array('Store', 'ItemID', 'Description', 'Price');
$result = array();
foreach($myArray as $innerArray)
{
$result[] = array_combine(
$newKeys,
array_values($innerArray)
);
}
array_combine() combines the first array you pass to it and assign it as the keys of the returned array and the second array you pass it as the values of that array.