0

我有这个数组,我尝试过迭代并创建一个新数组:

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)
      }
4

1 回答 1

1

您似乎正在尝试合并您的主题 ID 和相关主题 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()) 函数中。那不应该只设置一次。如果这是有道理的。

于 2013-02-18T21:14:00.300 回答