我在使用Key对数组进行分组时遇到问题:- 我有一个php数组,里面有以下元素。
$array = array(
'0' => array ( 'id' => 'food,Travel', 'names' => 'chimpanzee' ),
'1' => array ( 'id' => 'food', 'name' => 'meeting' ),
'2' => array ( 'id' => 'Z1', 'name' => 'dynasty' ),
'3' => array ( 'id' => 'X', 'name' => 'chocolate' ),
'4' => array ( 'id' => 'Travel', 'name' => 'bananas' ),
'5' => array ( 'id' => 'Travel', 'name' => 'fantasy' ),
'6' => array ( 'id' => 'Travel', 'name' => 'football' )
);
当我尝试以下代码时:-
$newarray= array();
foreach($array as $key => $value){
$newarray[$value['id']][$key] = $value;
}
我得到的结果均低于数组此处食物,旅行创建了另一个数组,但我想取悦于相应类别的“食物去食物”和“旅行去旅行”
(
[food,Travel] => Array
(
[0] => Array
(
[id] => food,Travel
[names] => chimpanzee
)
)
[food] => Array
(
[1] => Array
[id] => food,Travel
[names] => chimpanzee
)
(
[id] => food
[name] => meeting
)
)
[Z1] => Array
(
[2] => Array
(
[id] => Z1
[name] => dynasty
)
)
[X] => Array
(
[3] => Array
(
[id] => X
[name] => chocolate
)
)
[Travel] => Array
(
[4] => Array
(
[id] => Travel
[name] => bananas
)
[5] => Array
(
[id] => Travel
[name] => fantasy
)
[6] => Array
(
[id] => Travel
[name] => football
)
)
)
但是我想得到以下结果:-食物应该转到食物类别,而旅行应该转到旅行类别,例如:-
Array
(
[food] => Array
(
// Food should come at food category
[0] => Array
(
[id] => food
[names] => chimpanzee
)
)
(
[1] => Array
(
[id] => food
[name] => meeting
)
)
[Z1] => Array
(
[2] => Array
(
[id] => Z1
[name] => dynasty
)
)
[X] => Array
(
[3] => Array
(
[id] => X
[name] => chocolate
)
)
[Travel] => Array
(
( // Travel should come at travel category
[0] => Array
(
[id] => food
[names] => chimpanzee
)
)
[4] => Array
(
[id] => Travel
[name] => bananas
)
[5] => Array
(
[id] => Travel
[name] => fantasy
)
[6] => Array
(
[id] => Travel
[name] => football
)
)
)
答案 0 :(得分:0)
仅应将值添加到数组中。无需指定$ key
$newarray= [];
foreach($array as $key => $value){
$newarray[$value['id']][] = array_values($value);
}
答案 1 :(得分:0)
当id
有,
时,只需explode
,检查demo
$result = [];
foreach($array as $k => $v){
if(strpos($v["id"],",")) {
$ids = explode(",", $v["id"]);
foreach ($ids as $id) {
$result[$id][$k] = $v;
}
}else{
$result[$v["id"]][$k] = $v;
}
}
var_dump($result);
答案 2 :(得分:0)
不需要像某些人建议的那样使其复杂,请使用explode()
$newarray= [];
foreach($array as $key => $value) {
if(is_array(explode(",", $value["id"]))) {
foreach(explode(",", $value["id"]) as $category) {
$newarray[$category][$key] = $value;
$newarray[$category][$key]["id"] = $category;
}
} else {
$newarray[$value["id"]][$key] = $value;
}
}
var_dump($newarray);
您甚至可以删除$key
,因为它们会自动递增。
foreach($array as $value) {
if(is_array(explode(",", $value["id"]))) {
foreach(explode(",", $value["id"]) as $category) {
$value["id"] = $category;
$newarray[$category][] = $value;
}
} else {
$newarray[$value["id"]][] = $value;
}
}