PHP assign one array's values as a keys to another array's values if both arrays keys matches

1.6k views Asked by At
<?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>';
?>

Expected output:

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

There are 2 answers

0
Nambi On BEST ANSWER

try 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);

output:

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

3
sergio On

This work fine:

  $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);

Result:

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"
  }