我有这个数组,我尝试过迭代并创建一个新数组:
array(233) {
[0]=>
array(2) {
["subject_id"]=>
int(138)
["relatedsubject_id"]=>
int(127)
}
[1]=>
array(2) {
["subject_id"]=>
int(138)
["relatedsubject_id"]=>
int(47)
}
[2]=>
array(2) {
["subject_id"]=>
int(138)
["relatedsubject_id"]=>
int(13)
}
[3]=>
array(2) {
["subject_id"]=>
int(138)
["relatedsubject_id"]=>
int(56)
}
[4]=>
array(2) {
["subject_id"]=>
int(154)
["relatedsubject_id"]=>
int(77)
}
[5]=>
array(2) {
["subject_id"]=>
int(154)
["relatedsubject_id"]=>
int(69)
}
[6]=>
array(2) {
["subject_id"]=>
int(154)
["relatedsubject_id"]=>
int(70)
}
[7]=>
array(2) {
["subject_id"]=>
int(154)
["relatedsubject_id"]=>
int(75)
我把它剪短了,所以它不会太讨厌。这是我现在使用的代码:
$subject_id = array();
foreach ($results as $mainKey => $subArrays) {
if(!isset($subject_id[$results[$mainKey]["subject_id"]])) {
$subject_id[$results[$mainKey]["subject_id"]] = array();
array_push($subject_id[$results[$mainKey]["subject_id"]], $results[$mainKey]["relatedsubject_id"]);
// $subject_id[$results[$mainKey]["subject_id"]][] = $results[$mainKey]["relatedsubject_id"];
}
}
var_dump($subject_id);
我的结果如下所示:
array(111) {
[138]=>
array(1) {
[0]=>
int(127)
}
[154]=>
array(1) {
[0]=>
int(77)
}
关于为什么我只得到 1 个值以及如何修改以使每个“relatedsubject_id”符合相应的“subject_id”的任何想法?谢谢你。
编辑
预期结果:
array {
[138]=>
array(1) {
[0]=>
int(127)
[1]=>
int(47)
[2]=>
int(13)
[3]=>
int(56)
}
[154]=>
array(1) {
[0]=>
int(77)
[1]=>
int(69)
[2]=>
int(70)
[3]=>
int(75)
}