我有这样的数组。有一些名称相同的数组。例如Grant 1,Grant 2 ......他们有许多应该在同一个地方的项目。例如:Grant 1应包含属于Grant 1的信息。与Grant 2相同的事情。依此类推
array:5 [▼
0 => array:2 [▼
0 => "Grant 1"
1 => Project {#423 ▶}
]
1 => array:2 [▼
0 => "Grant 1"
1 => Project {#421 ▶}
]
2 => array:2 [▼
0 => "Grant 2"
1 => Project {#412 ▶}
]
3 => array:2 [▼
0 => "Grant 1"
1 => Project {#424 ▶}
]
4 => array:2 [▼
0 => "Grant 2"
1 => Project {#419 ▶}
]
]
我想将它们合并到:
array:5 [▼
0 => array:2 [▼
0 => "Grant 1"
1 => Project {#423 ▶}
2 => Project {#421 ▶}
3 => Project {#424 ▶}
]
1 => array:2 [▼
0 => "Grant 1"
1 => Project {#412 ▶}
2 => Project {#419 ▶}
]
]
请帮忙。谢谢,
答案 0 :(得分:0)
我认为你可以使用foreach
:
$newArray = [];
foreach ($array as $value) {
$newArray[$value[0]][] = $value[1];
}
你有这样的数组:
array:5 [▼
"Grant 1" => array:2 [▼
1 => Project {#423 ▶}
2 => Project {#421 ▶}
3 => Project {#424 ▶}
]
"Grant 2" => array:2 [▼
1 => Project {#412 ▶}
2 => Project {#419 ▶}
]
]
或类似的东西(感谢@AbraCadaver):
$newArray = [];
foreach ($array as $value) {
if (isset($newArray[$value[0]] {
$newArray[$value[0]][] = $value[1];
} else {
$newArray[$value[0]] = $value;
}
}
数组你需要的东西:
array:5 [▼
0 => array:2 [▼
0 => "Grant 1"
1 => Project {#423 ▶}
2 => Project {#421 ▶}
3 => Project {#424 ▶}
]
1 => array:2 [▼
0 => "Grant 1"
1 => Project {#412 ▶}
2 => Project {#419 ▶}
]
]