Combine two arrays on key/value and output combined array with PHP

后端 未结 2 928
刺人心
刺人心 2021-01-25 21:26

Racking my brain on this, found many examples of similar situations however the solutions don\'t seem to match up.

I have two arrays being built as the result of SQL que

相关标签:
2条回答
  • 2021-01-25 21:49

    Try this:

    foreach ($matchme as $arrProduct) {
        if (isset($data[$arrProduct['sku']])) {
            $arrMerged[$arrProduct['sku']]=array_merge($arrProduct, $data[$arrProduct['sku']]);
        }
    }
    
    print_r($arrMerged);
    

    The reason your code doesn't work is here:

    if(in_array($matchme[$key]['sku'], $data)) [...]
    

    What in_array() does is tell you whether your needle (in your case the SKU string) exists as a value of array haystack (in your case, $data). You are essentially trying to match a string to an array, rather than another string.

    What you really want is just to match the SKU string to the key of $data, for which isset() is probably the simplest approach.

    0 讨论(0)
  • 2021-01-25 22:01

    Assuming your first array as $first and second array as $second

    foreach ($first as $key => $each) {
      foreach ($second as $secondeach) {
        if($secondeach['sku'] == $key) {
          $first[$key] = array_merge($first[$key], $secondeach);
          // unset since you do not want LocalSKU value anymore.
          unset($first[$key]['LocalSKU']);
        }
      }
    }
    

    $first is your array you wanted.

    0 讨论(0)
提交回复
热议问题