php 中的函数 array_multisort 更改数组的键
function array_multisort in php change the key of my array
我有这个数组:
$array["4E-952778"][0]['fileName'] = "File 1";
$array["4E-952778"][0]['product'] = "Muse On Demand";
$array["4E-952778"][1]['fileName'] = "File 2";
$array["4E-952778"][1]['product'] = "Muse On Demand";
$array["15210"][0]['fileName'] = "File 3";
$array["15210"][0]['product'] = "4Manager";
$array["15210"][1]['fileName'] = "File 4";
$array["15210"][1]['product'] = "4Manager";
$products = array();
foreach ($array as $key => $row) {
$products[$key] = $row[0]['product'];
}
array_multisort($products, SORT_ASC, $array);
print_r($array);
结果是这样的:
Array
(
[0] => Array
(
[0] => Array
(
[fileName] => File 3
[product] => 4Manager
)
[1] => Array
(
[fileName] => File 4
[product] => 4Manager
)
)
[4E-952778] => Array
(
[0] => Array
(
[fileName] => File 1
[product] => Muse On Demand
)
[1] => Array
(
[fileName] => File 2
[product] => Muse On Demand
)
)
)
如您所见,函数 array_multisort()
将密钥:15210
更改为 0
为什么要更改?
引自manual:
Associative (string) keys will be maintained, but numeric keys will be re-indexed.
并且 PHP 会自动将您的字符串“15210”转换为整数。
这个方法的诀窍是在键(“015210”)中添加一个“0”,它会强制类型转换为(字符串)。
如果想了解更多信息,请参阅:Bug #21788 array_multisort() changes array keys unexpectedly given numeric strings as keys
我找到了解决这个问题的办法
uasort($array, function ($a, $b) {
$i=0;
return strcmp($a[$i]['product'], $b[$i]['product']);
});
我有这个数组:
$array["4E-952778"][0]['fileName'] = "File 1";
$array["4E-952778"][0]['product'] = "Muse On Demand";
$array["4E-952778"][1]['fileName'] = "File 2";
$array["4E-952778"][1]['product'] = "Muse On Demand";
$array["15210"][0]['fileName'] = "File 3";
$array["15210"][0]['product'] = "4Manager";
$array["15210"][1]['fileName'] = "File 4";
$array["15210"][1]['product'] = "4Manager";
$products = array();
foreach ($array as $key => $row) {
$products[$key] = $row[0]['product'];
}
array_multisort($products, SORT_ASC, $array);
print_r($array);
结果是这样的:
Array
(
[0] => Array
(
[0] => Array
(
[fileName] => File 3
[product] => 4Manager
)
[1] => Array
(
[fileName] => File 4
[product] => 4Manager
)
)
[4E-952778] => Array
(
[0] => Array
(
[fileName] => File 1
[product] => Muse On Demand
)
[1] => Array
(
[fileName] => File 2
[product] => Muse On Demand
)
)
)
如您所见,函数 array_multisort()
将密钥:15210
更改为 0
为什么要更改?
引自manual:
Associative (string) keys will be maintained, but numeric keys will be re-indexed.
并且 PHP 会自动将您的字符串“15210”转换为整数。
这个方法的诀窍是在键(“015210”)中添加一个“0”,它会强制类型转换为(字符串)。
如果想了解更多信息,请参阅:Bug #21788 array_multisort() changes array keys unexpectedly given numeric strings as keys
我找到了解决这个问题的办法
uasort($array, function ($a, $b) {
$i=0;
return strcmp($a[$i]['product'], $b[$i]['product']);
});