Combining arrays based on keys from another array

2019-08-30 00:27发布

问题:

I want to combine two arrays like this:

1st array:

   array( "ATTENDED"        => 1,
          "TENTATIVE"       => 2,  //
          "REJECTED"        => 3,
          "OUTSTANDING"     => 4,  
          "ACCEPTED"        => 6
        );

2nd Array:

  array ( 1 => 29, 
          4 => 30, 
          6 => 47 
        );

I want to get the results like this:

  array ( 'ATTENDED' => 29, 
          'OUTSTANDING' => 30, 
          'ACCEPTED' => 47
        );

2nd array is flexible. I can flip keys and values.

or better yet:

   array( "ATTENDED"    => 29,
      "TENTATIVE"       => 0,  //
      "REJECTED"        => 0,
      "OUTSTANDING"     => 30,  
      "ACCEPTED"        => 47
     );

I know there must be a simple solution. Any ideas?

回答1:

foreach ($arr1 as $k1 => $v1) {
    $arr1[$k1] = isset($arr2[$v1]) ? $arr2[$v1] : 0;
}

edit- This is without an explicit loop, although I don't think this is really better, but maybe cooler though.

$mapped = array_map(function($valFromArr1) use ($arr2) {
    return isset($arr2[$valFromArr1]) ? $arr2[$valFromArr1] : 0;
}, $arr1);

I can't think of a sane way to just use pure php functions.



回答2:

   $labels = array( 
          "ATTENDED"        => 1,
          "TENTATIVE"       => 2, 
          "REJECTED"        => 3,
          "OUTSTANDING"     => 4,  
          "ACCEPTED"        => 6
        );

    $values = array(
          1 => 29, 
          4 => 30, 
          6 => 47 
        );

   $results = array();

   foreach ($labels as $label => $id) {
       $results[$label] = array_key_exists($id, $values) ? $values[$id] : 0;
   }


标签: php arrays key