2016-12-29 54 views
1

我有一個PHP循環將數據推送到一個數組中,最終將用於在我的下拉列表中創建select選項列表。PHP嵌套陣列未對齊

我覺得它有點接近,但我在某處做錯了事。

types的數組需要成爲它所關聯的category的一部分。

// Get the list of behavior types 
public function _behavior_types() 
{ 

    $cat = $this->global_model->get_behavior_categories(); 
    $typ = $this->global_model->get_behavior_types(); 
    $output = array(); 

    // Loop over our categories 
    foreach($cat as $c) 
    { 
     // Push the category name to an array 
     $output[] = $c['categoryName']; 

     // Loop over our types 
     foreach($typ as $t) 
     { 
      // If this type belongs to the category we are currently in, add it to the array 
      if($t['categoryID'] == $c['categoryID']) 
      { 
       array_push($output, $t); 
      } 
     } 

    } 

    return $output; 
} 

我有一些東西的地方但是其造成的陣列不是正確的方式建立。

下面是電流輸出:

Array 
(
    [0] => Negative 
    [1] => Array 
     (
      [categoryID] => 2 
      [points] => -3 
      [typeID] => 4 
      [typeName] => Bad School Day 
     ) 

    [2] => Positive 
    [3] => Array 
     (
      [categoryID] => 1 
      [points] => 2 
      [typeID] => 1 
      [typeName] => Ate Dinner 
     ) 

    [4] => Array 
     (
      [categoryID] => 1 
      [points] => 2 
      [typeID] => 3 
      [typeName] => Brushed Teeth 
     ) 

    [5] => Array 
     (
      [categoryID] => 1 
      [points] => 3 
      [typeID] => 2 
      [typeName] => Completed Homework 
     ) 

) 

這是我想要的輸出:

Array 
(
    [0] => Negative 
     [0] => Array 
      (
       [categoryID] => 2 
       [points] => -3 
       [typeID] => 4 
       [typeName] => Bad School Day 
      ) 

    [1] => Positive 
     [0] => Array 
      (
       [categoryID] => 1 
       [points] => 2 
       [typeID] => 1 
       [typeName] => Ate Dinner 
      ) 

     [1] => Array 
      (
       [categoryID] => 1 
       [points] => 2 
       [typeID] => 3 
       [typeName] => Brushed Teeth 
      ) 

     [2] => Array 
      (
       [categoryID] => 1 
       [points] => 3 
       [typeID] => 2 
       [typeName] => Completed Homework 
      ) 

) 

反過來下拉的樣子:

Negative 
    Bad day at school 
Positive 
    Ate Dinner 
    Brushed Teeth 
    Completed Homework 

回答

4

你期望的輸出不真的是一個有效的數組結構,至少你是如何輸入的。 $output[0]不能同時爲字符串Negative和一組選項。我建議使類別的關鍵是這樣的:

// Get the list of behavior types 
public function _behavior_types() 
{ 

    $cat = $this->global_model->get_behavior_categories(); 
    $typ = $this->global_model->get_behavior_types(); 
    $output = array(); 

    // Loop over our categories 
    foreach($cat as $c) 
    { 
     // Push the category name to an array 
     $output[$c['categoryName']] = array(); 

     // Loop over our types 
     foreach($typ as $t) 
     { 
      // If this type belongs to the category we are currently in, add it to the array 
      if($t['categoryID'] == $c['categoryID']) 
      { 
       array_push($output[$c['categoryName']], $t); 
      } 
     } 

    } 

    return $output; 
}