PHP:根据array2值更改array1值

时间:2014-01-06 21:20:52

标签: php multidimensional-array

我有2个数组。有时,array1中的键/值可能等于array2的键/值。如果是这样,请将“status”从array2中的特定键/值更改为新值。这有意义吗?

我在这里:

foreach($array1 as $i=>$x){
          foreach($array2 as $k=>$y){
            if($x['url'] == $y['url']){

              // Up to here works

              foreach($i as &$value) {
                $value['status'] = 'new value';
            }

              break;
            }
          }
        }

这是我的阵列:

array(1) { 
    [0]=> array(1) {
        ["url"]=> string(104) "aHR0cDovL3lvdXR1YmUuY29t"
        ["date"]=> string(19) "2014-01-06 21:44:39"
        ["status"]=> string(1) "0"
     }

    [1]=> array(1) { 
        ["url"]=> string(28) "d3d3LnR3aXR0ZXIuY29t"
        ["date"]=> string(19) "2014-01-06 14:28:32"
        ["status"]=> string(1) "0"
     }
 } 

和array2:

array(2) { 
    [0]=> array(2) {
        ["url"]=> string(104) "aHR0cDovL3lvdXR1YmUuY29t"
        ["date"]=> string(19) "2014-01-06 21:44:39" 
     }

    [1]=> array(2) { 
        ["url"]=> string(28) "aHR0cDovL3d3dy5nb29nbGUuY29t"
        ["date"]=> string(19) "2014-01-06 14:28:32"
     }
 }

直到评论有效。从那以后,如何将特定键/值更改为新值?我当前的示例将所有关键“状态”更改为“新值”。

2 个答案:

答案 0 :(得分:1)

您不必再次通过array1循环,只需更改密钥

即可
$array1[$i]['status'] = 'new value';

答案 1 :(得分:1)

这个怎么样:

<?php
    $array1 = array(
        array(
            "url"   =>  "aHR0cDovL3lvdXR1YmUuY29t",
            "date"  =>  "2014-01-06 21:44:39",
            "status"    =>  "0"
            )
        );
    $array2 = array(
        array(
            "url"   =>  "aHR0cDovL3lvdXR1YmUuY29t",
            "date"  =>  "2014-01-06 21:44:39",
            )
        );

    array_walk($array2, function($arr2) use (&$array1)
    {
        foreach($array1 as &$arr1)
        {
            if($arr2['url'] == $arr1['url'])
                $arr1['status'] = "something";
        }
    });

    print_r($array1);

<强>输出

Array
(
    [0] => Array
        (
            [url] => aHR0cDovL3lvdXR1YmUuY29t
            [date] => 2014-01-06 21:44:39
            [status] => something
        )
)