PHP在foreach循环中将平面转换为嵌套的多维数组 [英] PHP convert flat to nested multidimensional array in foreach loop

查看:116
本文介绍了PHP在foreach循环中将平面转换为嵌套的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据以这种方式来自平面数组中的mysql查询:

I have some data that is coming from a mysql query in a flat array this way:

  0 => Array 
    indcode => "A00"
    indlabel => "Code label text"
    description => "More explanations"
  1 => Array 
    indcode => "NA0"
    indlabel => "Un-classified A"
    description => "Un-classified A"
  2 => Array (3)
    indcode => "A01"
    indlabel => "Code Label text"
    description => "More explanations"
  3 => Array (3)
    indcode => "A02"
    indlabel => "Code label text"
    description => "More explanations"

我想这样嵌套:

  A00 => Array 
    indlabel => "Code label text"
    description => "More explanations"
  NA0 => Array 
    indlabel => "Un-classified A"
    description => "Un-classified A"
  A01 => Array 
    indlabel => "Code Label text"
    description => "More explanations"
  A02 => Array
    indlabel => "Code label text"
    description => "More explanations"

因此,在我的CMS中,我发现使用了一个非常简洁的代码来嵌套:

So in my CMS I found in use a very neat code which does the nesting :

foreach ($dimsDesc as $desc) {
$descriptions[$desc['indcode']][$desc['indlabel']] = $desc['description'];
}

可以,但是我找不到如何将indlabel和描述保留在相同级别(=等号的另一侧)。

That works but I didn't find how to keep the indlabel and description at the same level (= the other side of the equal sign).

此外,如果您有一些其他示例的链接或该结构的良好参考,将不胜感激,因为我将大量使用它来构建动态报告。目前,PDO查询有点超出我的能力范围。我还使用了 array_column() NULL 的方法,但是可以接收到更复杂的数据结构...

Also, if you have links to some other examples or a good reference for this construct, it would be appreciated because I will use this a lot to build dynamic reports... And for now PDO queries are a bit out of my reach. I also used array_column() with NULL which works but I have more complex data structures incoming...

推荐答案

您快到了,只需按以下方式更改 foreach 循环,

You're almost there, just change your foreach loop in the following way,

foreach ($dimsDesc as $desc) {
    $descriptions[$desc['indcode']]['indlabel'] = $desc['indlabel'];
    $descriptions[$desc['indcode']]['description'] = $desc['description'];
}

或者,

foreach ($dimsDesc as $desc) {
    $descriptions[$desc['indcode']] = array('indlabel' => $desc['indlabel'], 'description' => $desc['description']);
}

这里是文档,

  • Creating/modifying arrays with square bracket syntax

这篇关于PHP在foreach循环中将平面转换为嵌套的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆