php - Change keys in each row of a 2d array without losing values
I have an array of rows where one (visual) column of data has two similar but different keys. I would like to replace one of the keys so that the column has the same key in all rows.
My input array:
[
['Ttitle' => 'lilly', 'Price' => 1.75, 'Number' => 3],
['Title' => 'rose', 'Price' => 1.25, 'Number' => 15],
['Title' => 'daisy', 'Price' => 0.75, 'Number' => 25],
['Title' => 'nettle', 'Price' => 2.75, 'Number' => 33],
['Title' => 'orchid', 'Price' => 1.15, 'Number' => 7],
];
My desired result: (notice the key change forlilly
)
[
['Title' => 'lilly', 'Price' => 1.75, 'Number' => 3],
['Title' => 'rose', 'Price' => 1.25, 'Number' => 15],
['Title' => 'daisy', 'Price' => 0.75, 'Number' => 25],
['Title' => 'nettle', 'Price' => 2.75, 'Number' => 33],
['Title' => 'orchid', 'Price' => 1.15, 'Number' => 7],
];
When I attempted to usearray_map()
, I manage to change all the keys toTitle
, but I also delete allTitle
values except for theTtitle
key I just changed toTitle
.
Code is as follows:
if (!empty($notmatchingarray))
{
$completearray = array_merge($notmatchingarray, $datastuff2);
$completearray = array_map(
function($complete) {
return array(
'Title' => $complete['Ttitle'],
'Price' => $complete['Price'],
'Number' => $complete['Number'],
);
},
$completearray
);
print_r($completearray);
}
Am I doing the wrong thing in using thisarray_map()
function? Should I be doing something else?
Answer
Solution:
Better ways but I'm headed out. With your existing code you need to set
Ttitle
orTitle
whichever is present:Ternary operator is a shortcut for a simple
if
/else
, so:Answer
Solution:
You might try using the
function:
Or if you prefer:
If the array
$complete
contains the key,'Title'
, it will use that; otherwise it will use the key'Ttitle'
.Answer
Solution:
Your rows of data are statically positioned, so honestly, you can just use iterated calls of
array_combine()
with your preferred keys.If your row elements are not predictably positioned, then you can simplify/modernize the earlier posted answers with the null coalescing operator.
Codes: (Demo)
Or: