我有一个多维数组,如下所示:
<?php
$array = array(
"categories" => array(
array(
array(
"arr1" => array(
'Name' => "some name associated with 300",
'availability' => true,
'amount' => 300
),
"arr2" => array(
'Name' => "some other name",
),
"arr3" => array(
'Name' => "some other name",
)
)
),
array(
array(
"arr1" => array(
'Name' => "some name associated with 59",
'availability' => true,
'amount' => 59
),
"arr2" => array(
'Name' => "some other name",
),
"arr3" => array(
'Name' => "some other name",
)
)
),
array(
array(
"arr1" => array(
'Name' => "some name associated with 100",
'availability' => true,
'amount' => 100
),
"arr2" => array(
'Name' => "some other name",
),
"arr3" => array(
'Name' => "some other name",
)
)
)
),
"departures" => array(
//..same as above arrays..
),
"arrivals" => array(
// ..same as above arrays..
),
//..more arrays
);
?>
我正在尝试按amount
键值(从最小到最大)对其进行排序,这样我就可以得到这样的结果:
$array = array(
"categories" => array(
array(
array(
"arr1" => array(
'Name' => "some name associated with 59",
'availability' => true,
'amount' => 59
),
"arr2" => array(
'Name' => "some other name",
),
"arr3" => array(
'Name' => "some other name",
)
)
),
array(
array(
"arr1" => array(
'Name' => "some name associated with 100",
'availability' => true,
'amount' => 100
),
"arr2" => array(
'Name' => "some other name",
),
"arr3" => array(
'Name' => "some other name",
)
)
),
array(
array(
"arr1" => array(
'Name' => "some name associated with 300",
'availability' => true,
'amount' => 300
),
"arr2" => array(
'Name' => "some other name",
),
"arr3" => array(
'Name' => "some other name",
)
)
)
),
"departures" => array(
//..same as above arrays..
),
"arrivals" => array(
//..same as above arrays..
),
);
我试图遍历数组并创建一个新数组,但我一再陷入困境......除非有完全不同的方法来做到这一点。你可以帮帮我吗?这是我到目前为止所尝试的:
$ordered_arr = array(
"departures" => array(),
"arrivals" => array(),
"categories" => array()
);
foreach ($array as $key => $arrOpts) {
$new_key = "";
foreach ($arrOpts as $arrVals) {
if (empty($ordered_arr[$key])) {
array_push($ordered_arr[$key], $arrVals);
} else {
var_dump();
/// this is where im stuck
}
}
}
答案 0 :(得分:1)
$categories = array();
foreach ($array['categories'] as $values) {
foreach ($values as $value) {
$categories[] = $value;
}
}
$amounts = array();
foreach ($categories as $category) {
foreach ($category as $v) {
if (isset($v['amount']) === true) {
$amounts[] = $v['amount'];
}
}
}
array_multisort($amounts, SORT_ASC, $categories);
foreach ($categories as &$category) {
$category = array($category);
}
unset($category);
$array['categories'] = $categories;
var_dump($array);