如何从PHP中的2个数组中选择不同的键和值并改变它们?

时间:2013-02-11 09:48:51

标签: php arrays

我有两个数组,如

Array(
        [name] => [asdfg]
        [city] => [anand]
)    

当前

Array(
        [name] => [ud]
        [state] => [anand]
)

现在我必须比较这两个数组,并希望更改已更改的当前数组键或值,并包含像

这样的元素
Array(
        [name] => [<span class='bold_view'> ud </span>]
        [<span class='bold_view'> state </span>] => [anand]
)

3 个答案:

答案 0 :(得分:0)

$current['name']="<span class='bold_view'> ".$current['name']." </span>";
$current['<span class='bold_view'> state </span>']=$current['state'];

我不得不说它没有多大意义,但在这里它是......

答案 1 :(得分:0)

复制此代码并执行:并查看视图源(Ctrl + u)

<?php

$prev   = array("name"=>"[asdfg]","city"=>"[anand]");
$curent = array("name"=>"[ud]","state"=>"[anand]");

$res    = array();
foreach($prev as $key=>$val){
   $res[$key]   = $val;
   if(array_key_exists($key,$curent)){
      $res[$key]   = "[<span class='bold_view'> ".$curent[$key]." </span>]";
   }
   if($new_key = array_search($val,$curent)){
      unset($res[$key]);
      $res["<span class='bold_view'> ".$new_key." </span>"]   = $val;
   }
}

print_r($res);

?>

答案 2 :(得分:0)

$arr_pre = array(
                  "name"=>"asdfg",
                  "city"=>"anand",
                  "address" => "anand",
);

$arr_current= array(
                    "name"=>"ud",
                    "state"=>"anand",
                    "address" => "ananda"
);

$result = array_diff_assoc($arr_current,$arr_pre);
    $count_curr = array_count_values($arr_current);
    $count_old  = array_count_values($arr_pre);

    foreach ($result as $key => $value){



        if(!array_key_exists($key,$arr_pre ))
        {
            $key_new = "<b>".$key."</b>";

            if(!in_array($value,$arr_pre))
            {
                $val = "<b>".$value."</b>";
            }

            else if((isset($count_curr[$value]) != isset($count_old[$value])))
            {
                $val = "<b>".$value."</b>";
            }
            else 
            {
                $val = $value;
            }

            unset($arr_current_info[$key]);
        }
        else {
            $key_new = $key;

            if(!in_array($value,$arr_pre))
            {
                $val = "<b>".$value."</b>";
            }

            else if((isset($count_curr[$value]) != isset($count_old[$value])))
            {
                $val = "<b>".$value."</b>";
            }
            else 
            {
                $val = $value;
            }
        }

        $arr_current_info[$key_new]=$val;

    }


    echo "<pre>";
    print_r($arr_current_info);  

我这样做了,我得到了完美的答案