Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP merge arrays by value for 2 different array value

Tags:

arrays

merge

php

I have tried to merge two different arrays into a single array. Can any one help me please?

i have array like this

[0] (Array)#2
  [rank] "579"
  [id] "1"
[1] (Array)#4
  [rank] "251"
  [id] "2"

[0] (Array)#2
  [size] "S"
  [rank] "251"
[1] (Array)#15
  [size] "L"
  [rank] "579"

i need like this

[0] (Array)#2
  [size] "S"
  [rank] "251"
  [id] "1"
[1] (Array)#15
  [size] "L"
  [rank] "579"
  [id] "1"
like image 688
user3686600 Avatar asked Jul 02 '15 07:07

user3686600


2 Answers

Untested, but this should work, or at least get you close.

for ($array1 as $key1 => $value1) {
    for ($array2 as $key2 => $value2) {
        if ($value1['rank'] == $value2['rank']) {
            $result[$key1] = [$value2['size'], $value1['rank'], $value1['id']];
        };
    };
};
like image 53
glend Avatar answered Sep 29 '22 07:09

glend


foreach($arr1 as $key1 => $data1){
    foreach($arr2 as $key2 => $data2){
        if($data1['rank']==$data2['rank']){
            $result[] = array_merge($data1, $data2);
        }
    }
}
print_r($result);
like image 40
Ambal Mani Avatar answered Sep 29 '22 06:09

Ambal Mani