Create an Array with a KEY if values exists in two

2019-09-20 12:26发布

问题:

I am having problem with handling arrays. I want to "compare" two arrays to see if there's matching "usernames" in both arrays. I am not sure if I am using in_array() function properly

this is how my arrays look like:

USER array 1:

 Array ( [0] => Array ( [username] => LNDP [station] => D08 ) 
        [1] => Array ( [username] => ACMAN [station] => D06 )
        [2] => Array ( [username] => VTER [station] =>  D13 )
      )

    //the users will have to be matched with memo_code
    $user = array();
    while($row = mysqli_fetch_assoc($get_user_result)){
        $user[] = array( "username" => $row['username'],
                         "station"  =>  $row['station_number']                                                          
                            );
    }

MEMO array 2:

 Array (   [0] => Array ( [username] => VTER[aht_value] =>  333 ) 
           [1] => Array ( [username] => ACMAN [aht_value] => 456 ) 
           [2] => Array ( [username] => ACYL [aht_value] =>  789 )
         )


$memo = array();
    while ($row = mysqli_fetch_assoc($dbh2_result)){   
        $memo[] = array( "username"  => $row['memo_code'],
                       "aht_value" => $row['avg_handle_time']
                      );
    }

I want to check every "username" in my MEMO array to match the "username" in my USER array. If they do match, I want to create an array with username, station, aht_value like so:

Array ( [0] => Array ( [username] => ACMAN [aht_value] => 456 [station] => D06 ) 
      )

//creating array 3 by comparing 1 and 2 by using key value of "username" from array 2
    $result = array();
    //$m = key
    //$m['username'] = key value
    foreach($memo as $m => $m['username']){

        //if username in array 2 is in array 1
        if( in_array( $m, $user) ){
            //if aht_value is not null
            if( $memo['aht_value'] != null ){
            $result[] =  "username: " . $user['username'] . "aht_value: " .$m['aht_value'] . "position: " . $user['position']. "<br>";   
            }
            //else if aht_value is null
            else{
                $result[] = "username: " . $user['username'] . "aht_value: NA  position: " . $user['position'] . "<br>";
            }
        }
        //if there is no matching username do something?
        else{
            echo "no match";
        }

    }

    $final_result = json_encode($result);
    echo $final_result;

error message

Warning: Cannot use a scalar value as an array in line 97 : 
foreach($memo as $m => $m['username']){

If I need to clarify things please ask. After successfully creating the third array I will use json_encode to make an AJAX call and use type GET.

Thanks in advance for the help!

回答1:

instead of downvoting can someone please tell me what would be best to edit

First, people do not need to provide a reason for downvote, even if they did you wouldn't necessarily get anything constructive, just "I disagree" - "the question is poor".

Second, the question is not 100% clear, your code was a little rough around the edges before editing and when you got the downvotes, and is still unclear even after the edits.

You also do not state why your current attempt fails, what it does, what it is supposed to do, etc.

The issues

Your arrays do not seem to have matching keys to be able to pair anything up, especially given they 2nd dimension, trying to access cross section values which have no matching keys is very complicated.

It's not impossible, but given the huge code block required to try to make sense of your data, it's just not practical. A re-think in how you use the data is needed really.

EG
array_1 has keys of "username" and "station", yet your array_2 has keys of "memo_code" and "aht_value. There is no way to correlate from one thing to another using keys because there are no key pairs from one array to another.

When you loop an array, say array_1, you can get a matching value in array_2 from the current loop's value from array_1, but you do not have the index of array_2's value which is matched from array_1, you just have the value, which means you cannot obtain additional data from array_2, as you only have a value match, and not an index.

It's messy, really, especially given your scenario is really not complex enough to warrant such a complex scenario - in fact no scenario should really do the above, as there's nearly always a better "approach" rather than producing such a poor "fix".

Other solution

Why in array_2 is there a key "memo_code" which seems to be "username" from array_1?
It must be as you are wanting to marry up "username" with "memo_code".
So why not have "username" in array_2 as well, if that's what it is?

Going further, again I could be wrong but this is based on the info in your question - why not just have "aht_value" in array_1 and have no array_2?

Maybe there is a need for two arrays, which is not shown in your question, however what I get from your (confusing and a little garbled) question, is this "could" be fine:

$single_array = array 
    ( "0" => Array ( "username" => "LNDP", "station" => "D08", "aht_value" => "whatever") 
      "1" => Array ( "username" => "ACMAN", "station" => "D06", "aht_value" => "something" )
      "2" => Array ( "username" => "VTER", "station" => "D13", "aht_value" => NULL )
    );

You can get all values in one go which relate to the one username, even if they are on different tables just do a join (I presume you have foreign keys/relationships between the two tables.

If you need two arrays

If you need to keep both arrays (for whatever reason your scenario demands) and you cannot change this approach, then can you at least change it to have some kind of corresponding index in each array?
You could then can match one index from another, then take data from the matched pair.

Such as your indexes could be the usernames:

$user = array ( "LNDP" => Array ( "station" => "D08" ) 
                "ACMAN" => Array ( "station" => "D06" )
                "VTER" => Array ( "station" => "D13" )
              );


$memo = array ( "VTER" => Array ( "aht_value" => ""  ) 
                "ACMAN" => Array ( "aht_value" => "456" ) 
                "ACYL" => Array ( "aht_value" =>  "789" )
              );

Then loop one of the arrays, and where index (username) matches, you can get the rest of the data from that index easily and append it to a new array.

If you really must do it the way you have asked

Again, it is not impossible, but you'd need a huge block of code which would:

  1. Loop array_1 and get a matching value pair from array_2 from the current loop's value
  2. Use the identified value from array_2 and access the 2nd array separately and find the matching value's index
  3. Use the found index to get the additional data required
  4. Append it to the "new" array
  5. Start going through the loop again

Hope some of this helps.



回答2:

I found the solution after understanding arrays and key values.. these are two possible answer if ever someone wants to do something similar.

answer 1 :

foreach ($memo as $i => $memodata) {
    foreach ($user as $j => $userdata) {
    if ($memodata['username'] == $userdata['username']) {
        if (is_null($memodata['aht_value'])) {
        $result[] = "username: " . $userdata['username'] . " aht_value: NA  position: " . $userdata['station'];
      } 
      else {
        $result[] =  "username: " . $userdata['username'] . " aht_value: " .$memodata['aht_value'] . " position: " . $userdata['station'];   
      }
    } 
    }

answer 2:

foreach ($memo as $username => $memodata) {
    if (in_array($username, array_keys($user))) {
        // Match username against the keys of $user (the usernames) 
        $userdata = $user[$username];
        if (is_null($memodata['aht_value'])) {
            $result[] = array( 'username'  => $userdata['username'],
                                             'aht_value' => 'NA',
                                             'station'  => $userdata['station']
                                            );
        } 
    else {
        $result[] = array( 'username'  => $userdata['username'],
                                             'aht_value' => substr($memodata['aht_value'],0,-3),
                                             'station'   => $userdata['station']
                                            );
         }
    }
}