Php 将mySQL结果构造为多维数组
下面的代码从mySQL连接中获取一个包含一系列行的数组,并将它们重新构造为多维数组Php 将mySQL结果构造为多维数组,php,loops,multidimensional-array,foreach,Php,Loops,Multidimensional Array,Foreach,下面的代码从mySQL连接中获取一个包含一系列行的数组,并将它们重新构造为多维数组 foreach($content as $cont){ if(!$pagecontent){ $pagecontent = $cont; $pagecontent['theme'] = array(); } $themearray = array( 'themeID' => $cont['themeID'], 'th
foreach($content as $cont){
if(!$pagecontent){
$pagecontent = $cont;
$pagecontent['theme'] = array();
}
$themearray = array(
'themeID' => $cont['themeID'],
'theme_type' => $cont['theme_type'],
'theme_file' => $cont['theme_file'],
'theme_default' => $cont['theme_default'],
'theme_title' => $cont['theme_title'],
$cont['meta_field'] => $cont['meta_value']
);
array_push($pagecontent['theme'], $themearray);
}
下面是打印的输出阵列
Array
(
[contentID] => 9
[type] => operations
[title] => CTK Partners
[parent] => 8
[theme] => Array
(
[0] => Array
(
[themeID] => 2
[theme_type] => general
[theme_file] => logo
[theme_default] => 1
[theme_title] => CTT Group
[src] => uploads/img/clogo.png
)
[1] => Array
(
[themeID] => 2
[theme_type] => general
[theme_file] => logo
[theme_default] => 1
[theme_title] => CTT Group
[title] => CTT Industries
)
[2] => Array
(
[themeID] => 5
[theme_type] => general
[theme_file] => logo
[theme_default] => 0
[theme_title] => CTT Logo 2
[src] => uploads/img/cttlogo2.png
)
[3] => Array
(
[themeID] => 5
[theme_type] => general
[theme_file] => logo
[theme_default] => 0
[theme_title] => CTT Logo 2
[title] => CTF Associates
)
)
)
问题是,我想按ID号列出主题数组,以便重复写入的字段只插入尚未定义的字段
我期待的结果是:
Array
(
[contentID] => 9
[type] => operations
[title] => CTK Partners
[parent] => 8
[theme] => Array
(
[themeID2] => Array
(
[themeID] => 2
[theme_type] => general
[theme_file] => logo
[theme_default] => 1
[theme_title] => CTT Group
[src] => uploads/img/clogo.png
[title] => CTT Industries
)
[themeID5] => Array
(
[themeID] => 5
[theme_type] => general
[theme_file] => logo
[theme_default] => 0
[theme_title] => CTT Logo 2
[src] => uploads/img/cttlogo2.png
[title] => CTF Associates
)
)
)
如何实现这一点?为
$pagecontent['theme']
中的每一行指定一个键,如中所示
$pagecontent['theme']["themeID{$cont['themeID']}"] = $themearray;
代替
数组\u push
行。Dan的回答是正确的,但没有考虑到循环可能需要添加到主题数组而不覆盖它。他的代码的这种改编考虑到了这一点
if(!$pagecontent['theme']["themeID{$cont['themeID']}"]){
$pagecontent['theme']["themeID{$cont['themeID']}"] = $themearray;
}
else {
$pagecontent['theme']["themeID{$cont['themeID']}"][$cont['meta_field']] = $cont['meta_value'];
}
很好。但它没有考虑到可能需要添加一个额外的字段。我修改了您的代码,因此它也可以用于此目的,因此获得1票。我的答案是下面使用您的代码。这很正常,但如果你发现问题,一定要告诉我。谢谢