0

I want to sort the array based on their sku alphabetically and I wrote this program with three foraeach loop, I think I did not write it as the best solution, do you know any other better?what is your idea about it?

$array[] =  array('data' => array('entity_id' => 3446,'sku' => 'A'));
$array[] =  array('data' => array('entity_id' => 3546,'sku' => 'D'));
$array[] =  array('data' => array('entity_id' => 7446,'sku' => 'C'));
$array[] =  array('data' => array('entity_id' => 2446,'sku' => 'B'));
$array[] =  array('data' => array('entity_id' => 7446,'sku' => 'E'));
$array[] =  array('data' => array('entity_id' => 9446,'sku' => 'F'));

foreach ($array as $key => $data) {
    foreach ($data as $k=> $v)
        {
    $newarray[$key]  = $v['sku'];
        }
            }

asort($newarray);

foreach ( $newarray as $k=>$v)
$keys[]=$k;

$result=array();
foreach($keys as $k=>$v) {
    $result[$k] = $array[$v];
}
1

1 Answer 1

2

Assuming you want to sort just the outer array, all you need is a custom sort function:

usort($array, "sort_by_sku");

function sort_by_sku($a, $b) {
    return strcmp($a["data"]["sku"], $b["data"]["sku"]);
}
Sign up to request clarification or add additional context in comments.

Comments

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.