0

I have an array and I want to sort it:

$ArrayStock = array(array("SIZE","L","XL","M"),("STOCK","12","3","2"));

How can I sort the array by "SIZE"?

Alternatively, I could use this array as a starting point:

$ArrayStock = array(array("L","XL","M"),("12","3","2"));
7
  • you can't, because for some stupid reason "size" is part of your array and not a key Commented May 14, 2017 at 19:44
  • ok, how to sort if i delete "size" and "stock" ? so like this $ArrayStock = array(array("L","XL","M"),("12","3","2")); Commented May 14, 2017 at 19:48
  • make it associative Commented May 14, 2017 at 19:48
  • make a usort() function Commented May 14, 2017 at 19:50
  • It probably would be easier to change your array to be $arrayStock = [ 'size' => [ "L" => [ 'stock' => 12 ], "XL" => [ 'stock' => 3 ], "M" => [ 'stock' => 3 ] ] ]; Commented May 14, 2017 at 19:53

2 Answers 2

1

You could do it like this:

// Combine into one associative array
$combined = array_combine($ArrayStock[0], $ArrayStock[1]);

// Rebuild it in the correct order:
foreach(["SIZE", "S","M","L","XL","XXL"] as $size) {
    if (isset($combined[$size])) $result[$size] = $combined[$size];
}

// Split associative array back to its original structure:
$ArrayStock = [array_keys($result), array_values($result)];

Note that this structure is not so practical in its use. I would in fact stick with the associative array.

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

Comments

0

There will be a few ways to skin this cat. All of my methods will produce the expected output...

First, let's do it without restructuring your array (Demo):

$order=["XS","S","M","L","XL","2XL","3XL"];  // declare appropriate size order
$ArrayStock=[["L","XL","M"],["12","3","2"]];

// Order the first subarray:
uasort($ArrayStock[0],function($a,$b)use($order){
    return (array_search($a,$order)>array_search($b,$order)?1:-1);  // any unidentifed sizes will go to the front
});

// Sync the second subarray with first subarray:
$ArrayStock[1]=array_replace($ArrayStock[0],$ArrayStock[1]);

// Optionally re-index the keys:
$ArrayStock[0]=array_values($ArrayStock[0]);
$ArrayStock[1]=array_values($ArrayStock[1]);


Next I'll show a few ways that you can manipulate a restructured array. There is absolutely nothing wrong with the way that trincot has written his. These are just alternatives that I've come up with...

I agree with trincot about using sizes as keys (because they will be unique) and stock counts as values. So the first process is to generate that new array structure:

$ArrayStock=[["L","XL","M"],["12","3","2"]];

#1 One-liner array_combine() approach:

$new_structure=array_combine($ArrayStock[0],$ArrayStock[1]);
//  $new_structure = ['L'=>'12','XL'=>'3','M'=>'2']

#2 foreach() approach:

foreach($ArrayStock[0] as $i=>$size){
    $new_structure[$size]=$ArrayStock[1][$i];
}
//  $new_structure = ['L'=>'12','XL'=>'3','M'=>'2']

Now to sort the new array, you can use uksort() or a range of other array functions / loops with your predetermined order array:

$order=["XS","S","M","L","XL","2XL","3XL"];  // declare whatever appropriate sizes in order

#1 uksort() with array_search() approach:

uksort($new_structure,function($a,$b)use($order){
    return (array_search($a,$order)>array_search($b,$order)?1:-1);
    // any unidentified sizes will go to the front of the array
});
// keep in mind, this doesn't declare $result, it sorts $new_structure

#2 array_replace() with array_flip()-array_intersect()-array_keys() approach:

$result=array_replace(                         // replace values on matching keys
            array_flip(                        // swap keys with values
                array_intersect(
                    $order,                    // keep values from here
                    array_keys($new_structure) // that exist here
                )
            ),
        $new_structure);                       // use these elements for replace
// $result=['M'=>'2','L'=>'12','XL'=>'3'];

#3 foreach() with array_intersect()-array_keys() approach:

// generate & iterate ordered array
foreach(array_intersect($order,array_keys($new_structure)) as $v){
    $result[$v]=$new_structure[$v];      // build properly sorted array
}
// $result=['M'=>'2','L'=>'12','XL'=>'3'];

Finally as trincot has shown, you can revert the sorted data back to the initial format with one more one-liner:

$ArrayStock=[array_keys($result),array_values($result)];

3 Comments

@HengkyST Sorry for the long-winded answer. You can most-simply just use the two step method that I start with, or you can restructure your array and use any of the many techniques to sort the data. I mostly wanted to use your question to educate readers. Let me know if anything doesn't work for you or if you don't understand something I've written.
I Very Thanks full for complate tutorial $ArrayStock @mickmackusa, i try and it's work for me.
@HengkyST The pleasure is mine. I always learn more by experimenting/teaching.

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.