2014-05-14 57 views
-2

我正在處理一個數組,我已經得到了答案,但我需要爲我的數組再添加一個數組層。下面是我的例子:如何使數組變成子數組?

這是我的數組:

$newOptions = array(); 
    foreach ($community_comment as $option) { 
     $date = $option['date']; 
     $text = $option['text']; 

     $newOptions[$date][] = $text; 
    } 

,這是我的結果:

Array 
(
    [2014-05-14] => Array 
     (
      [0] => test test test test 
      [1] => test2 
     ) 

) 

,但我想我的結果是這樣的:

Array 
    (
     [0]=>Array(
      [2014-05-14] => Array 
      (
       [0] => test test test test 
       [1] => test2 
      ) 
    ) 
    ) 

希望我能得到一些幫助。先謝謝了。

+0

只需添加'$ newOptions = array($ newOptions,)'。 – Holt

+0

試試$ newOptions [] [$ date] [] –

回答

0

這應該爲你做它:

$newOptions = array(); 
foreach ($community_comment as $option) { 
    $date = $option['date']; 
    $text = $option['text']; 

    $newOptions[][$date][] = $text; 
} 
0

你只需要改變
$newOptions[$date][] = $text;

$newOptions[][$date][] = $text;

0
$i = 0; 
$fake_array = array(); 
foreach ($community_comment as $option) { 
    $date = $option['date']; 
    $text = $option['text']; 

    if(isset($fake_array[$date])) { 
     $newOptions[$fake_array[$date]][$date][] = $text; // $fake_array[$date] = old index 
    } 
    else { 
     $newOptions[$i][$date][] = $text; 
     $fake_array[$date] = $i; 
    } 
    $i++; 
} 
0
$newOptions = array(); 
    foreach ($community_comment as $option) { 
     $date = $option['date']; 
     $text = $option['text']; 

     $newOptions[][$date][] = $text; 
    } 
0

我已經找到了我的答案,這答案適合於實施在我的項目中。

foreach ($community_comment as $option) { 
     $date = $option['date']; 
     $text = $option['text']; 
     $id = $option['id']; 

     $data['text'] = $text; 
     $data['id'] = $id; 
     $newOptions[$date][] = $data; 
    } 

    $result = array(); 
    foreach ($newOptions as $key=>$value) 
    { 
     $result['date'] = $key; 
     $result['data'] = $value; 

     $result2[]=$result; 
    }