2

I want to add an item to a sub array and sort the array by a new order.

Here is my data:

$number = '112';
$user = 2;

And this is my array:

array( 
1 => array(111, 109, 108), 
2 => array(110, 107, 105), 
3 => array(99, 97, 96) 
)

I want to add a value in this array and sort it by a new order. So, my array needs to end up like this:

array( 
2 => array(112, 110, 107, 105), 
1 => array(111, 109, 108), 
3 => array(99, 97, 96) 
)

How can I do this quickly?

Payden K. Pringle
  • 61
  • 1
  • 2
  • 19
Tushar
  • 118
  • 11
  • 3
    whats the sort pattern? array with most values? highest number? –  Nov 17 '17 at 02:26
  • Yes. The sort pattern is highest number – Tushar Nov 17 '17 at 02:33
  • This link might help you: [How do I sort a multidimensional array by one of the fields of the inner array in PHP?](https://stackoverflow.com/questions/2426917/how-do-i-sort-a-multidimensional-array-by-one-of-the-fields-of-the-inner-array-i) – Asif Mehmood Nov 17 '17 at 02:47

1 Answers1

3

Assuming there would be a case where there's a number in the user's array greater than $number

$number = '112';
$user = 2;

$array = array(
1 => array(111, 109, 108),
2 => array(110, 107, 105),  
3 => array(99, 97, 96) 
);

$array[$user][] = $number; // add number to user's array
rsort($array[$user]);      // sort highest to lowest
$array = array($user => $array[$user]) + $array; // move the newly modified array to first element

echo '<pre>';
print_r($array);
Goma
  • 2,018
  • 1
  • 10
  • 19