我有一个数组,我已经尝试迭代并创建一个新数组:
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)
}
您似乎正在尝试合并主题id和相关的subject_id。如果是这样的话,这可能对你有用。
$subject_id = array();
foreach ($results as $mainKey => $subArrays) {
if(!isset($subject_id[$results[$mainKey]['subject_id']])) {
$subject_id[$results[$mainKey]['subject_id']] = array('subject_id' => $results[$mainKey]['subject_id'], 'relatedsubject_id' => array());
}
$subject_id[$results[$mainKey]['subject_id']]['relatedsubject_id'][] = $results[$mainKey]["relatedsubject_id"];
}
已更改为您的EDIT
$subject_id = array();
foreach ($results as $mainKey => $subArrays) {
if(!isset($subject_id[$results[$mainKey]['subject_id']])) {
$subject_id[$results[$mainKey]['subject_id']] = array();
}
$subject_id[$results[$mainKey]['subject_id']][] = $results[$mainKey]["relatedsubject_id"];
}
之所以只得到一个结果,是因为if(!isset())函数中包含了所有代码。这不应该只设置一次。如果这有道理的话。