Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 比较数组并将值从一个数组替换到另一个数组_Php_Arrays - Fatal编程技术网

Php 比较数组并将值从一个数组替换到另一个数组

Php 比较数组并将值从一个数组替换到另一个数组,php,arrays,Php,Arrays,我有两个数组需要比较和替换某些值 第一个数组类似于 Array ( [catID1] => Cat1 [catID2] => Cat2 [catID3] => Cat3 ... ) 其中,所有键都是从数据库中提取的CAT(数组值)的类别ID 第二个数组看起来像 Array ( [itemID1] => Item_cat1 [itemID3] => Item_cat2 [item

我有两个数组需要比较和替换某些值

第一个数组类似于

Array
(
    [catID1] => Cat1
    [catID2] => Cat2
    [catID3] => Cat3
    ...
)
其中,所有键都是从数据库中提取的CAT(数组值)的类别ID

第二个数组看起来像

Array
    (
        [itemID1] => Item_cat1
        [itemID3] => Item_cat2
        [itemID4] => Item_cat3
        ...
    )
其中,所有键都是项目ID,所有值都是项目类别

我需要做的是遍历第二个数组,如果第二个数组的值等于第一个数组的值,则用第一个数组中的数字键替换文本值

差不多

if( item_cat1 == cat1 )
{
    item_cat1 == catID1
}
但是我想创建一个新数组来保存这些值。数组应该如下所示

Array
(
    [itemID1] => catID2
    [itemID3] => catID4
    [itemID4] => catID1
    ...
)
我在两个数组的foreach循环的外部和内部尝试了array_intersect()和array_merge()的几种不同变体,但都没有成功。有人有什么建议吗?我想得太多了吗?

使用下面的
array\u search()
函数,
$items\u by\u catID
将为您提供一个项目数组(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);

?>