I have two arrays that I need to compare and replace certain values.
The first array looks similar to
Array
(
[catID1] => Cat1
[catID2] => Cat2
[catID3] => Cat3
...
)
Where all the keys are the category ids of the cats (array values) pulled from a database.
The second array looks like
Array
(
[itemID1] => Item_cat1
[itemID3] => Item_cat2
[itemID4] => Item_cat3
...
)
Where all keys are the item ids and all values are item categories.
What I need to do is go through the second array and replace the textual values with numeric keys from the first array if the value of the second array value is equal to the value of the first array.
something like
if( item_cat1 == cat1 )
{
item_cat1 == catID1
}
but i would like to create a new array to hold the values. the array should look like
Array
(
[itemID1] => catID2
[itemID3] => catID4
[itemID4] => catID1
...
)
I've tried several different variations of array_intersect() and array_merge() outside and inside of foreach loops on both arrays to no avail. Anyone have a suggestion? Am I overthinking this?
Using array_search()
function, $items_by_catID
below will give you an array of items (itemID => categoryID).
<?php
$categories = array
(
1 => "Category 1",
2 => "Category 2",
3 => "Category 3"
);
$items = array
(
1 => "Category 1",
3 => "Category 2",
4 => "Category 3"
);
$items_by_catID = array();
foreach ($items as $key => $category)
$items_by_catID[$key] = array_search($category, $categories, true);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.