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];
}
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"]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.