0

在 PHP 中,我有一个数组,如下所示:

array(35) {
[0] => array(11) {
'dept_number' → str•4 '2310'
'dept_descr' → str•10 'Some Stuff'
}

[1] => array(11) {
'dept_number' → str•4 '1010'
'dept_descr' → str•11 'Other Stuff'
}
...and so on

我有另一个数组如下:

array(22) {
[2310] => str•6 'Bakery'
[1010] => str•4 'Beer'
...and so on

我想用第二个数组中的描述替换第一个数组中的 dept_descr,其中第一个数组中的 dept_number 与第二个数组中的键匹配。所以,结果将是:

array(35) {
[0] => array(11) {
'dept_number' → str•4 '2310'
'dept_descr' → str•6 'Bakery'
}

[1] => array(11) {
'dept_number' → str•4 '1010'
'dept_descr' → str•4 'Beer'
}

这是怎么做到的?

4

4 回答 4

0

尝试这个:

$original = array(
    array(
        'dept_number' => 2310,
        'dept_descr' => 'Some Stuff'),
    array(
        'dept_number' => 1010,
        'dept_descr' => 'Other Stuff'));

$descriptions = array(
    2310 => 'Bakery',
    1010 => 'Beer');

foreach($original as &$element) {
    $element['dept_descr'] = $descriptions[$element['dept_number']];
}

print_r($original);

输出:

Array
(
    [0] => Array
        (
            [dept_number] => 2310
            [dept_descr] => Bakery
        )

    [1] => Array
        (
            [dept_number] => 1010
            [dept_descr] => Beer
        )
)
于 2013-09-17T22:49:03.470 回答
0

您可以使用array_walk

$array1 = ...; // Your first array
$array2 = ...; // Your second array

function descReplace(&$item) {
    $item['dept_descr'] = $array2[$item['dept_number']];
}

array_walk($array1, 'descReplace');
于 2013-09-17T22:49:11.383 回答
0
    foreach($array(22) as $key=>$value{
      foreach ($array(35) as $target){
         if($target['dept_number'] == $key) $target['dept_descr'] = $value.
      }
}

名称 $array(22) 和 $array(35) 不是实名。将这些替换为正确的数组名称。

于 2013-09-17T22:49:43.383 回答
0
$arr1 = array(35) {
    [0] => array(11) {
    'dept_number' ? str•4 '2310'
    'dept_descr' ? str•10 'Some Stuff'
    }

    [1] => array(11) {
    'dept_number' ? str•4 '1010'
    'dept_descr' ? str•11 'Other Stuff'
    }
}
$arr2 = array(22) {
    [2310] => str•6 'Bakery'
    [1010] => str•4 'Beer'
}

$arr2Keys = array_keys ($arr2);
foreach ($arr1 as $data) {
    if(in_array($data['dept_number'], $arr2Keys)) {
        $data['dept_descr'] = $arr2[$data['dept_number']];
    }
}
于 2013-09-17T22:58:02.437 回答