0

I hope somebody can help me, I need to order array No.1 based on the position of array no.2 , using the array1->id to array2->products_id

Array No.1

{"products":[{"id": 9847760515,"title":"Some Dress"},{"id": 10769647619,"title":"Shirt"}]}

Array No.2 where the order is: (position":x)

{"collects":[{"id":38447047939,"product_id":10769647619,"position":1,"sort_value":"0000000001"},{"id":25425594499,"product_id":9847760515,"position":3,"sort_value":"0000000003"}]}

foreach ($sorted_array as $product) {
 echo $product['name'];
}

Appreciate any help

Sam
  • 2,856
  • 3
  • 18
  • 29
user3466947
  • 1,227
  • 2
  • 11
  • 13

2 Answers2

0

You can create a function which will take both arrays and order them by whatever format you need it to be in:

/**
* sort_array will take two arrays and will sort the first based on the second
*
* @param $array the array you want to reorder
* @param $order the array with the pattern
*
* @return array_multisort with reordered array
*/
function sort_array(&$array, $order, $dir = SORT_ASC) {

    // create an empty array here
    $sort = array();

    // loop through the main array
    foreach ($array as $key => $row) {
        $sort[$key] = $row[$order];
    }

    array_multisort($sort, $dir, $array);
}

Using array_multisort you can "sort multiple or multi-dimensional arrays." For more information on that you can read it on PHP Manual; with further information on how it can be used.


I based this answer with previously answered question on Stack Overflow.

Sam
  • 2,856
  • 3
  • 18
  • 29
  • Hi Samuel, thanks for the answer, I had already seen the other answer before, but can you show me an example using my arrays? – user3466947 Sep 02 '17 at 23:20
0

You can use usort function supplying it with order from the second array:

$sort = array_combine(
    array_column($array2, 'product_id'),
    array_column($array2, 'position')
);

usort($array1, function ($a, $b) use ($sort) {
    return $sort[$a['id']] - $sort[$b['id']];
});

We prepare sorting dictionary ($sort) by using array_combine and array_column functions. Pay attention, that in order to use array_column function you have to convert your JSON to an array of arrays (pass true as the second argument of json_decode function).

Here is working demo.

sevavietl
  • 3,762
  • 1
  • 14
  • 21