在数组中搜索值匹配并替换值 - php

时间:2013-10-12 23:54:23

标签: php arrays

感谢您的帮助,我坚持这个问题。让我解释一下,我有这种阵列。

First Array
--------------
Array
(
    [2] => value7
    [3] => value8
    [4] => value9
    [5] => value10
    [6] => value11
    [7] => value12
    [8] => value13
)
Second Array
--------------
Array
(
    [0] => Array
        (
            [0] => 5
            [1] => 3
            [2] => 6
        )

    [1] => Array
        (
            [0] => 8
            [1] => 4
            [2] => 7
        )
)

和期望的结果: (如果第二个数组值==第一个数组键;更改第二个数组值)

Array
(
    [0] => Array
        (
            [0] => value10
            [1] => value8
            [2] => value11
        )

    [1] => Array
        (
            [0] => value13
            [1] => value9
            [2] => value12
        )
)

2 个答案:

答案 0 :(得分:1)

我认为你没有正确地向你展示阵列。这是否回答了你的问题?

foreach($secondArray as $i => $v){
  if($firstArray[$v])$secondArray[$i] = $firstArray[$v];
}

答案 1 :(得分:1)

如果我们认为您的arrays是这样的:

$array1 = array(
     2 => 'value7',
     3 => 'value8',
     4 => 'value9',
     5 => 'value10',
     6 => 'value11',
     7 => 'value12',
); 
$array2 = array(
    array(
        10 => 5,
        1 => 7,
        2 => 4,
     ),
    array(
        0 => ''
    ),
    array(
        0 => 3
    )    
); 

然后这将完成工作:

$keys1 = array_keys($array1);
foreach($array2 as $innerKey => $innerArray) {
    foreach($innerArray as $k => $val) {
        if(in_array($val, $keys1)) {
            $array2[$innerKey][$k] = $array1[$val];
        }
    }
}
var_dump($array2);

输出

array (size=3)
  0 => 
    array (size=3)
      10 => string 'value10' (length=7)
      1 => string 'value12' (length=7)
      2 => string 'value9' (length=6)
  1 => 
    array (size=1)
      0 => string '' (length=0)
  2 => 
    array (size=1)
      0 => string 'value8' (length=6)