Foreach数组组织/迭代

时间:2013-02-18 20:51:31

标签: php for-loop multidimensional-array foreach iteration

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

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

1 个答案:

答案 0 :(得分:1)

您似乎正在尝试合并主题ID和relatedsubject_ids。如果是这样,这可能适合你。

    $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"];
    }

已更改为您的编辑

$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())函数中拥有所有代码。这应该只设置一次。如果这是有道理的。