Php 在4级数组中对章节进行排序
我想将现有数组排序为4维数组: 我拥有的“列表”数组:Php 在4级数组中对章节进行排序,php,arrays,sorting,multidimensional-array,Php,Arrays,Sorting,Multidimensional Array,我想将现有数组排序为4维数组: 我拥有的“列表”数组: 1 => "text1" 10 => "text10" 11 => "text11" 101 => "text101" 1011 => "text1011" 10123 => "text10123" 2 => "text2" 20 => "text20" 201 => "text201" 2011 => "text2011" 20111
1 => "text1"
10 => "text10"
11 => "text11"
101 => "text101"
1011 => "text1011"
10123 => "text10123"
2 => "text2"
20 => "text20"
201 => "text201"
2011 => "text2011"
20111 => "text20111"
我想要的数组是一个按每个数字(4维)对所有数据进行排序的数组。我的意思是,在$chapter[1]的末尾,我不会有另一个数组包含10123=>“text1023”(这个数组将与这个数组位于同一个数组中:1011=>“text1011”
下面是我想要的数组示例
$chapter[1] = array(
1 => "text1", array(
10 => "text10", 11 => "text11", array(
101 => "text101", array(
1011 => "text1011", 10123 => "text10123" )
)
)
);
我想您可以使用
for loop
将每个数字分解为数字(带),然后添加数组
考虑以下示例:
$arr = array(1, 11, 111, 113, 2, 21, 211, 213);
$chapter = array(); // this will be your result array
foreach($arr as $e) {
$digits = str_split($e);
$current = &$chapter;
foreach($digits as $d) {
if (!isset($current[$d]))
$current[$d] = array();
$current = &$current[$d];
}
}
请注意,我使用&
将新数组分配给原始结果数组
我知道您的数组缺少键,不需要排序,但我想您可以克服它(之前对数组进行筛选和排序)
已编辑
问题更改后,这是示例代码:(当keyDATA
用于所需文本,keyCHILDREN
用于下一个元素时)
请添加有关您的问题的更多信息,并添加您尝试过的内容。您好,请查看此指南。您缺少的代码不起作用。如果您希望免费解决问题,这不是堆栈溢出的目的。更准确地说:1.更详细地描述您需要的结果,您显示的示例不可描述e足够多并且包含错误;2.展示您尝试过的内容;3.描述您的尝试是如何失败的。在这种情况下,该问题将被视为高质量问题,其他用户将乐于提供帮助。非常感谢您,但是您如何为每个键分配值1将有House示例和111 Car您分配值是什么意思?y可以吗你请用desire output更新你的问题?目前它在你的问题中起作用。你意识到这与原来的帖子非常不同,对吗?并且key不能有两个值,因此你的desire output无效-因为key“1”不能同时有两个“text1”其余部分的数组-仅当它们也封装在数组下时…是的,我的意思是它们封装在数组下。数组下有一个数组作为numbers@jason9根据您的更新编辑了答案-请同时编辑您问题的标题-目前未对问题进行描述
$arr = array(1 => "text1", 10 => "text10", 11 => "text11", 101 => "text101", 1011 => "text1011", 10123 => "text10123", 2 => "text2", 20 => "text20", 201 => "text201", 2011 => "text2011", 20111 => "text20111");
$chapter = array();
foreach($arr as $key => $val) {
$digits = str_split(substr($key, 0, 4)); // if 4 digits is the max depth
$current = &$chapter;
foreach($digits as $d) {
if (!isset($current["CHILDREN"][$d]))
$current["CHILDREN"][$d] = array();
$current = &$current["CHILDREN"][$d];
}
$current["DATA"] = $val;
}