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

StackOverflow https://stackoverflow.com/questions/20605429

  •  02-09-2022
  •  | 
  •  

Question

<?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"
    )
Was it helpful?

Solution

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 )

OTHER TIPS

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"
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top