1, "TENTATIVE"...">

Combining arrays based on keys from another array

I want to combine two arrays as follows:

1st array:

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

code> Second array:

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

code>

I want to get the following results:

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

code>

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

or better yet:

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

code> I know there should be a simple solution. Any ideas?

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

Edit- This is without an explicit loop, although I do not think it is really better, but perhaps cooler.

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

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

+3
source
   $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;
   }
0
source

All Articles