2013-02-18 62 views
0

我有這樣的陣列,我試過遍歷並創建一個新的數組:的foreach陣列組織/迭代

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

你可以發佈你想讓你的數組看起來像嗎? – 2013-02-18 21:07:02

回答

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

你之所以只得到一個結果是你有在如果(!isset()函數)函數中的所有代碼。這應該只能設置一次。如果這是有道理的。

+0

啊,我現在看到了。非常感謝。 – JohnSchaum 2013-02-18 21:21:59