php - Merge/Replace associative rows from one array with the associative rows of another array
I have 2 arrays - one is hard coded and the other is data retrieved from a database. I am trying to merge them but I'm having unexpected results.
This is the first array:
$base_image_array = [
["product_image_one" => ""],
["product_image_two" => ""],
["product_image_three" => ""],
["product_image_four" => ""]
];
This is the second array:
$db_product_images = [
["product_image_one" => "../wp-content/themes/dosco/images/products_images/355_product_image_one.jpg"],
];
However, when I tryarray_merge($base_image_array, $db_product_images)
, I get 5 rows and theproduce_image_one
occurs more than once.
What I want to achieve is this:
[
['product_image_one' => '../wp-content/themes/dosco/images/products_images/355_product_image_one.jpg'],
['product_image_two' => ''],
['product_image_three' => ''],
['product_image_four' => '']
]
I think the multidimensional nature of the arrays is confusing me.
Answer
Solution:
clean up your num indexed array to kv array
output
Answer
Solution:
The problem is that the array keys in both arrays are numeric. If you want one array to overwrite the other you need to get them into a state where the array keys are strings. You could do something like this:
There are probably better ways to loop through this with the php array functions - but this should get the job done!
Answer
Solution:
The solution was very similar to the answer by @Matthew R.
The resulting output was like so:
The final output was actually different to what I originally thought I needed.
Answer
Solution:
I recommend directly flattening the result because assuming these subarray keys are unique, there is no benefit to the depth of the data structure. You can unpack the two arrays with
...
(spread operator) and feed the individualized row data toarray_replace()
(orarray_merge()
) to achieve the same conceptual result:Code: (Demo)
Output:
If you desperately need to keep the deep structure, you can recreate the initial depth by mapping every associative element as its own row.