2011-01-26 28 views
1

我有两个数组,我需要比较并替换某些值。比较数组并将数组从一个数组替换为另一个数组

第一个数组类似于

Array 
(
    [catID1] => Cat1 
    [catID2] => Cat2 
    [catID3] => Cat3 
    ... 
) 

,所有的按键都是猫(数组值)的类别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 
    ... 
) 

我试过array_intersect()和array_merge(几种不同的变化),外部和内部的foreach循环两个阵列无济于事的。任何人都有建议?我是否在说这个?

回答

3

使用array_search()函数,$items_by_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); 

?> 
相关问题