PHP在foreach循环中将flat转换为嵌套的多维数组

时间:2016-10-09 01:01:43

标签: php arrays multidimensional-array

我有一些数据来自平面数组中的mysql查询:

  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中我发现使用了一个非常简洁的代码来进行嵌套:

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

这有效,但我没有找到如何将indlabel和描述保持在同一级别(=等号的另一侧)。

此外,如果您有其他一些示例的链接或此构造的良好参考,我将不胜感激,因为我将使用它来构建动态报告...而现在PDO查询有点不在我的达到。我还使用array_column()NULL一起工作,但我有更复杂的数据结构传入......

2 个答案:

答案 0 :(得分:1)

试试这个,

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

答案 1 :(得分:1)

你几乎就在那里,只需按照以下方式更改foreach循环,

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']);
}

这是文档,