php - Merge and sort associative arrays -


first array:

array (      [0] => array ( [id] => 1 [occ] => 14 )      [1] => array ( [id] => 2 [occ] => 12 )      [2] => array ( [id] => 4 [occ] => 2 )  ) 

second array:

array (      [0] => array ( [id] => 1 [company_name] => google   [ceo] => mike )      [1] => array ( [id] => 2 [company_name] => apple    [ceo] => jones)      [2] => array ( [id] => 2 [company_name] => bmw      [ceo] => steve)      [3] => array ( [id] => 3 [company_name] => hardsoft [ceo] => lucy )      [4] => array ( [id] => 4 [company_name] => lays     [ceo] => morty)  ) 

i merge these arrays that:

array (      [0] => array ( [id] => 1 [company_name] => google   [ceo] => mike   [occ] => 14)      [1] => array ( [id] => 2 [company_name] => apple    [ceo] => jones  [occ] => 12)      [2] => array ( [id] => 3 [company_name] => bmw      [ceo] => steve  [occ] => 0)      [3] => array ( [id] => 4 [company_name] => hardsoft [ceo] => lucy   [occ] => 2)      [4] => array ( [id] => 5 [company_name] => lays     [ceo] => morty  [occ] => 0)  ) 

then sort them occ google first, apple second, hardsoft third , on.

how can archive it?

this should work you:

first of use array_column() array id's first array "lookup table". use array_values() reindex second array.

after start looping through second array , reassigning id, using key innerarray + 1. don't have duplicate id's.

then array_search() if new id in lookup table , if yes assign value occ first array second array. if not assign 0 value of key occ in second array.

after done, simple sort usort() compare values of occ , sort it's value (note: if want change sorting desc asc change < > in usort() call).

<?php      $ids = array_column($arr1, "id");     $arr2 = array_values($arr2);      foreach($arr2 $k => &$v) {         $v["id"] = ($k+1);         if(in_array($v["id"], $ids))             $arr2[$k]["occ"] = $arr1[array_search($v["id"], $ids)]["occ"];         else             $arr2[$k]["occ"] = 0;     }                 usort($arr2, function($a, $b){         if($a["occ"] == $b["occ"])             return 0;         return $a["occ"] < $b["occ"] ? 1 : -1;     });      print_r($arr2);  ?> 

output:

array (     [0] => array         (             [id] => 1             [company_name] => google             [ceo] => mike             [occ] => 14         )      //...      [4] => array         (             [id] => 3             [company_name] => bmw             [ceo] => steve             [occ] => 0         )  ) 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -