2014-03-13 180 views
0

我正在處理動態數據,所以我試圖將這些數據放入一個二維數組中。動態生成的二維數組

我需要這樣的結構:

$array['something1'] = array ('hi1' => 'there1' , 'hi2' => 'there2'); 

所有這些數據是由一個foreach動態生成,例:

$list = array (0 => 'something;hi1;there1' , 1 => 'something;hi2;there2'); 


foreach ($list as $key => $data) 
{ 
    // extract data 
    $columns = explode (';' , $data); 

    // set data 
    $items[$columns[0]] = array ($columns[1] => $columns[2]); 
} 

我該怎麼辦先前描述的?

現在劇本正在加緊比上年鍵得到的東西是這樣的:

$array['something1'] = array ('hi2' => 'there2'); 

我希望你能幫助我。

謝謝。

回答

1

的問題是,你的關鍵覆蓋值時,它已經存在。你應該修改類似於:

foreach ($list as $key => $data) 
{ 
    // extract data 
    $columns = explode (';' , $data); 
    $outer_array_key = $columns[0]; 
    $key = $columns[1]; 
    $value = $columns[2]; 

    // set data 
    $items[$outer_array_key][$key] = $value; 
} 
+0

感謝您的支持!我不知道發生了什麼事情:S我已經寫了一個返回$ items [$ outer_array_key] [$ key]的方法。我想我的想法崩潰了一陣子xD – Lucas

0

像這樣的東西改變你的一組數據:

if(!array_key_exists($columns[0], $items)) 
    $items[$columns[0]] = array(); 
$items[$columns[0]][$columns[1]] = $columns[2]; 
1
Here is how it can be done: 


$list = array (0 => 'something;hi1;there1' , 1 => 'something;hi2;there2'); 

$newlist =array(); 
foreach($list as $k=>$v){ 

    $items = explode(';',$v); 
    $newlist[$items[0]][$items[1]]=$items[2]; 
} 


echo "<pre>"; 
print_r($newlist); 
echo "</pre>"; 


//output 
/* 
Array 
(
    [something] => Array 
     (
      [hi1] => there1 
      [hi2] => there2 
     ) 

)*/ 

?>