我的数据库中有一个数组,如下所示:
[0] => Array
(
[titre] => Quality
[type_de_contenu] => pdf
)
[1] => Array
(
[titre] => Quality
[type_de_contenu] => doc
)
[2] => Array
(
[titre] => Video
[type_de_contenu] => video
)
从这个阵列我想得到:
array(
"Quality"=>array(
array(
"titre"=>"Quality and certifications",
"type_de_contenu" => doc
),
array(
"titre"=>"Quality and certifications 2",
"type_de_contenu" => pdf
),
),
"video"=>array(
"titre" => "video",
"type_de_contenu" => "video"
)
)
如你所见,我希望将所有数组与相同的标题值组合在一个数组中,我有任何想法,而且我的所有尝试都不好。
你能帮我吗?
谢谢你们
答案 0 :(得分:2)
尝试这样的事情:
$tmpArr = array();
foreach($dbArr as $k => $v)
{
if (!isset($tmpArr[$v['titre']]))
$tmpArr[$v['titre']] = array();
$tmpArr[$v['titre']][] = $v;
}
var_dump($tmpArr);
答案 1 :(得分:0)
您可以选择使用:https://github.com/jakezatecky/array_group_by
print_r(array_group_by($source, 'titre'));
但是一个简单的foreach循环就可以了。
<?php
$source = [
[
"titre" => "Quality",
"type_de_contenu" => "pdf",
],
[
"titre" => "Quality",
"type_de_contenu" => "doc",
],
[
"titre" => "Video",
"type_de_contenu" => "video",
],
];
$target = [];
foreach($source as $sub){
$target[$sub['titre']][] = $sub;
}
print_r($target);
// will result in:
Array
(
[Quality] => Array
(
[0] => Array
(
[titre] => Quality
[type_de_contenu] => pdf
)
[1] => Array
(
[titre] => Quality
[type_de_contenu] => doc
)
)
[Video] => Array
(
[0] => Array
(
[titre] => Video
[type_de_contenu] => video
)
)
)
答案 2 :(得分:0)
请尝试使用此
$array = array(
array(
'titre'=>"Quality",
'type_de_contenu'=>"pdf"
),
array(
'titre'=>"Quality",
'type_de_contenu'=>"doc"
),
array(
'titre'=>"video",
'type_de_contenu'=>"video"
)
);
print_r('<pre>');
print_r($array);
$target_array = array();
foreach($array as $array1 ){
$target_array[$array1['titre']][] = array(
'titre'=>"title text",
'type_de_contenu'=>$array1['type_de_contenu']
);
}
print_r('<pre>');
print_r($target_array);