我有一个多维数组,我想按字母顺序对第二级值进行排序
$shop = array(
"director" => Array
(
"0" => 'Sushil Majumdar',
"1" => 'Jyotirmoy Ray',
"3" => 'Phani Gangopadhyay',
"5" => 'Chitta Bose',
"6" => 'Satyajit Ray',
"7" => 'Ajoy Kar'
),
"producer" => Array
(
"0" => 'Bharat Lokchitram Ltd.',
"1" => 'Lokbani Chitrapratisthan',
"2" => 'Rama Chhayachitra',
"3" => 'Poddar Pictures',
"4" => 'Rama Chhayachitra Ltd.',
"5" => 'Chhayachitra Parishad',
"6" => 'Government of West Bengal',
"7" => 'Bikash Ray Productions',
"8" => 'Epic Films'
)
);
$keys = array('director'=>1);
foreach ($shop as $k => $v){
if(array_key_exists($k, $keys)){
foreach ($v as $ke => $ve){
sort($shop[$k]);
}
}
}
虽然它可以排序但不知何故它在我的结果中没有受到影响 那么我怎样才能按字母顺序按升序排序我的数组值
答案 0 :(得分:0)
您的代码段正常运行。但是,用于迭代$ v的每个循环在排序中没有任何作用。所以你可以删除那个。 保持喜欢;
foreach ($shop as $k => $v){
if(array_key_exists($k, $keys)){
sort($shop[$k]);
}
}
print_r($shop); //alphabetically sorted values under "director" key
如果您打印$ shop数组,您会发现“director”键下的值按字母顺序排序。
答案 1 :(得分:0)
您可以使用以下函数在第二级对数组进行排序:
function sortOnKeys($array, array $keys) {
foreach ($array as $k => $v){
if(array_key_exists($k, $keys)){
sort($array[$k]);
}
}
return $array;
}
/* set your keys */
$keys = array('director' => 1, 'producer' => 2);
/* invoke the sorting function */
$sorted = sortOnKeys($shop, $keys);
echo '<pre>';
var_dump($sorted);
echo '</pre>';