0

I have this array $mergeArr:

  array (size=5)
  'facebook' => 
    array (size=3)
      'facebook_enabled' => string '1' (length=1)
      'facebook_url' => string 'https://www.facebook.com/' (length=25)
      'facebook_order' => string '7' (length=1)   //order element
  'twitter' => 
    array (size=3)
      'twitter_enabled' => string '1' (length=1)
      'twitter_url' => string 'https://www.twitter.com/' (length=24)
      'twitter_order' => string '9' (length=1)   //order element
  'instagram' => 
    array (size=3)
      'instagram_enabled' => string '1' (length=1)
      'instagram_url' => string 'https://www.instagram.com/' (length=26)
      'instagram_order' => string '2' (length=1)  //order element
  'linkedin' => 
    array (size=3)
      'linkedin_enabled' => string '1' (length=1)
      'linkedin_url' => string 'https://www.linkedin.com/' (length=25)
      'linkedin_order' => string '5' (length=1)  //order element
  'pintrest' => 
    array (size=3)
      'pinterest_enabled' => string '1' (length=1)
      'pinterest_url' => string 'https://www.pinterest.com/' (length=26)
      'pinterest_order' => string '3' (length=1)  //order element

I need to sort it according the *_order element in each array.

I tried the code below:

CODE PHP:

array_multisort(array_column($mergeArr, '2'), SORT_ASC, $mergeArr);

Expected output order is: Instagram, Pinterest, Linkedin, Facebook, Twiter.

The error that I receive is the following

array_multisort(): Array sizes are inconsistent

Can you please tell me how can I sort this array so I get what I want?

Thanks in advance!

7
  • The $mergeArr doesn't have key "2" - so it is size 0 and the original $mergeArr is size 5 -> that why the inconsistent Commented Jul 15, 2019 at 7:19
  • ok and how should I write the new form of code? Commented Jul 15, 2019 at 7:20
  • I am little bit confuse: what is you input? the first (bigger) array you shared on the one in the code example? according to what do you need the sort? Commented Jul 15, 2019 at 7:22
  • - in the first example I present the form of array before sorting. Commented Jul 15, 2019 at 7:25
  • Possible duplicate of array_multisort(): Array sizes are inconsistent Commented Jul 15, 2019 at 7:25

1 Answer 1

3

If the field to compare is always in the 3-th key you can do that with usort and array-values as:

usort($array, function($a, $b) {
    $a = array_values($a);
    $b = array_values($b);
    return $a[2] > $b[2];
});

Live example: 3v4l

Sign up to request clarification or add additional context in comments.

1 Comment

ok but this example also works with more than two elements? can you please fill out the example with all 5 values?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.