如果两个数组键匹配,PHP将一个数组的值指定为另一个数组值的键

时间:2013-12-16 07:23:01

标签: php arrays array-key

<?php
echo '<pre>';

$directnames = array("LN"=>"ListingId","LAG"=>"AgentCode","ST"=>"MlsStatus","LP"=>"ListPrice","PIC"=>"PhotosCount");

$result = array("LN"=>"129_551453","LAG"=>"2.50","ST"=>"3.00","LP"=>"Ferndale","PIC"=>"359900.00");


$directnames_getkeys = array_keys($directnames);
$result_getkeys = array_keys($result);
$merge_keys = array_intersect($directnames_getkeys,$result_getkeys);
$assigning = array();

foreach($merge_keys as $preparevalues){
    foreach($directnames[$preparevalues] as $keys){
        echo $assigning[$keys] = $result[$preparevalues];
    }
}


echo '</pre>';
?>

预期输出:

array(
    "ListingId"=>"129_551453",
    "AgentCode"=>"2.50",
    "MlsStatus"=>"3.00",
    "ListPrice"=>"Ferndale",
    "PhotosCount"=>"359900.00"
    )

2 个答案:

答案 0 :(得分:1)

尝试array_combine()

$directnames = array("LN"=>"ListingId","LAG"=>"AgentCode","ST"=>"MlsStatus",
        "LP"=>"ListPrice","PIC"=>"PhotosCount");

         $result = array("LN"=>"129_551453","LAG"=>"2.50","ST"=>"3.00",
    "LP"=>"Ferndale","PIC"=>"359900.00");


            $a=array_combine($directnames,$result);
            print_r($a);

<强>输出

Array([ListingId] =&gt; 129_551453 [AgentCode] =&gt; 2.50 [MlsStatus] =&gt; 3.00 [ListPrice] =&gt; Ferndale [PhotosCount] =&gt; 359900.00)

答案 1 :(得分:0)

这项工作很好:

  $directnames = array("LN"=>"ListingId","LAG"=>"AgentCode","ST"=>"MlsStatus","LP"=>"ListPrice","PIC"=>"PhotosCount");

$result = array("LN"=>"129_551453","LAG"=>"2.50","ST"=>"3.00","LP"=>"Ferndale","PIC"=>"359900.00");


foreach($directnames as $value){
    $resultArray[][$value]= current($result);
    next($result);
}


var_dump($resultArray);

<强>结果:

array(1) {
    ["ListingId"]=>
    string(10) "129_551453"
  }
  [1]=>
  array(1) {
    ["AgentCode"]=>
    string(4) "2.50"
  }
  [2]=>
  array(1) {
    ["MlsStatus"]=>
    string(4) "3.00"
  }
  [3]=>
  array(1) {
    ["ListPrice"]=>
    string(8) "Ferndale"
  }
  [4]=>
  array(1) {
    ["PhotosCount"]=>
    string(9) "359900.00"
  }