Reputation: 9
I have two arrays, the first has keys, which exist as values in the second array. I'd like to identify the keys in the first array, that exist as values in the second array. And in the second array, i'd like to change the value (that is the key in the first array) to the value of the key in the first array.
First Array
Array
(
**[sequence]** => 2344
**[imbarcode]** => DTTDTADDFDTADTDTAAATDFAFTTFDDAAFFFTTAADFADDDFATADADDFATDDDTDFTDFD
**[first]** => Lisa A
**[last]** => Dedrick
**[address]** => 4019 Nightington Dr
**[city]** => Province
**[st]** => PA
**[zip]** => 10059-1702
)
Second Array
Array
(
[deleted_on] =>
[universe_id] => 1
[street] => **address**
[city] => **city**
[state] => **st**
[zip] => **zip**
[check_digit] => **sequence**
[carrier_route] => **imbarcode**
)
Desired result
Array
(
[deleted_on] =>
[universe_id] => 1
[street] => **4019 Nightington Dr**
[city] => **Province**
[state] => **PA**
[zip] => **10059-1702**
[check_digit] => **2334**
[carrier_route] => **DTTDTADDFDTADTDTAAATDFAFTTFDDAAFFFTTAADFADDDFATADADDFATDDDTDFTDFD**
)
This could be done with multiple foreachs, but i'd like to find a less expensive way to do this as there could be a massively large number of arrays we're essentially mapping.
Full story
The first array, is one of what could be thousands (from a csv). So if we have 50,000 line items in the csv, we'll have 49,999 arrays. The second array, will always have four arrays (they'll correlate to a database). The end result, (with the above csv example) should have one mass array, with 4 sub arrays, where each sub-array has 49,999 arrays within it.
Not very efficient with PHP however, it's what I am limited to currently.
Any help is greatly appreciated.
EDIT
Here is what I have that atleast maps the values (does not retain the other values I need)
foreach ($data as $key => $val) {
foreach ($csv as $k => $v) {
foreach ($val as $dk => $dv) {
foreach ($v as $ck => $cv) {
if ($dv == $ck) {
$res[$dk] = $cv;
}
}
}
$result[$key][] = $res;
}
}
$this->out(print_r($result,true));
I don't want to foreach this many times.
SOLVED.
Solution
foreach ($data as $key => $val) {
foreach ($csv as $ck => $cv) {
$result[$key][] = str_replace(array_keys($cv), $cv, $val);
}
}
Upvotes: 0
Views: 1328
Reputation: 78984
I assume you use the **
to highlight things as print_r
would not display it that way, rather [**address**]
. But str_replace
supports arrays, so search the second array for the keys in the first array and replace with the values of the first array:
$result = str_replace(array_keys($first), $first, $second);
Upvotes: 1
Reputation: 6006
Only one foreach is needed.
foreach ($arr2 as $key => $value) {
$arr2[$key] = $arr1[$value] ?? $value;
}
Upvotes: 1