peace_love
peace_love

Reputation: 6471

How can I combine two arrays by key and value?

This is my array "products":

array:3 [▼
  0 => array:8 [▼
    "uuid" => "78f895684c"
    "Name" => "test1"
  ]
  1 => array:8 [▼
    "uuid" => "f71db561ba"
    "Name" => "Zwei"
  ]
  2 => array:8 [▼
    "uuid" => "3e231651de"
    "Name" => "Test3"
  ]
]

This is my array "category":

array:3 [▼
  "78f895684c" => "pink"
  "f71db561ba" => "blue"
  "3e231651de" => "pink"
]

I try to create a new array, that sort my products into the category. This is my approach:

 foreach ($products as $key => $value) {
   $test = $category[$value["uuid"]];
   $new[$test] = array();
   array_push($new,$value);
 }

The result I expect is:

array:5 [▼
  "blue" => 
     [0] => array:2 [▼
      "uuid" => "f71db561ba"
      "Name" => "Zwei"
  ]
  "pink" => 
    [1] => array:2 [▼
       "uuid" => "78f895684c"
       "Name" => "test1"
    [2] => array:2 [▼
    "uuid" => "3e231651de"
    "Name" => "Test3"
  ]
]

But my result is:

array:5 [▼
  "pink" => []
  0 => array:8 [▼
    "uuid" => "78f895684c"
    "Name" => "test1"
  ]
  "blue" => []
  1 => array:8 [▼
    "uuid" => "f71db561ba"
    "Name" => "Zwei"
  ]
  2 => array:8 [▼
    "uuid" => "3e231651de"
    "Name" => "Test3"
  ]
]

Upvotes: 0

Views: 53

Answers (2)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

You can do something like this: $new[$cat][] = $value;

Example:

$new = array();

foreach ($products as $prod) {
  $cat = $category[$prod['uuid']];

  $new[$cat][] = $prod;
}

Working demo here

Upvotes: 1

Alberto
Alberto

Reputation: 12949

you are pushing the element into the wrong array with

array_push($new,$value);

because you need to insert it into $new[$test] so instead do

array_push($new[$test],$value);

Also check if the $new[$test] already exists, otherwise create the array:

if(!$new[$test]) $new[$test] = array();

So at the end the code is

foreach ($products as $key => $value) {
   $test = $category[$value["uuid"]];
   if(!$new[$test]) $new[$test] = array();
   array_push($new[$test],$value);
} 

Upvotes: 1

Related Questions