0

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
  • Take a look at the array_merge function. Commented Apr 23, 2012 at 18:34

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Possible without loop? I don't need 0, if its only possible with loop. First output is fine too.
0
   $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;
   }

4 Comments

Thanks. But I there must a solution without loop!
In another language I would suggest a functional approach using map or similar, but PHP's level of support for such things makes solutions that use them somewhat clunky.
This is the output I get: Array ( [ATTENDED] => 1 [TENTATIVE] => 1 [REJECTED] => 1 [OUTSTANDING] => [ACCEPTED] => )
See edited answer. someone dropped their Perl into my PHP code. :) But with the fix, my answer is essentially the same as @chris's, so you should accept his before mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.