以下代码获取一个包含mySQL JOIN中一系列行的数组,并将它们重构为多维数组。
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
)
)
)
如何实现这一目标?
答案 0 :(得分:1)
为$pagecontent['theme']
中的每一行指定一个键,如
$pagecontent['theme']["themeID{$cont['themeID']}"] = $themearray;
代替array_push
行。
答案 1 :(得分:0)
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'];
}