2010-07-05 117 views
0

好的......我討厭數組的......我不理解他們,也不喜歡和他們一起工作......但我正在一個項目中工作,我無法控制數據,但需要一種方法把它整理成我可以操縱的格式...通過嵌套的PHP數組操作和循環

因此,數據看起來是這樣的:

$arr = Array ( 
[1] => Array ([December] => a date here [December (2)] => a location here... [December (3)] => an event here...) 
[2] => Array ([December] => a date here [December (2)] => a location here... [December (3)] => an event here...) 
[3] => Array ([December] => a date here [December (2)] => a location here... [December (3)] => an event here...) 
[4] => Array ([December] => a date here [December (2)] => a location here... [December (3)] => an event here...) 
[5] => Array ([December] => a date here [December (2)] => a location here... [December (3)] => an event here...) 
) 

首先,我需要改變「月」,「十二月(2 )'&'December(3)'to'Date','Location'&'Event'...

然後,我需要一種方法來引用每個數組中的新鍵,然後我可以將其插入到數據庫中?

喜歡的東西:

$arr[1][Date]; 

,但我想$改編[1]將需要類似$改編[$ i] ...?

有人可以幫我這個嗎?這將是非常讚賞...我試圖讓這個正確的某個時候...

+2

你最好開始習慣數組,它們是PHP的心臟,靈魂,麪包和黃油。 – deceze 2010-07-05 01:19:30

+1

我改變了標題,因爲你的問題與排序無關。 – Artefacto 2010-07-05 01:22:17

+0

是的,好多了,謝謝! – Indigo 2010-07-05 01:38:14

回答

1

首先,我需要改變「月」,「十二月(2)」 &「十二月(3)」到'日期」, '位置' & '事件' ......

foreach ($arr as &$a) { 
    $a["Date"] = $a["December (2)"]; 
    unset($a["December (2)"]); 
    $a["Location & Event"] = $a["December (3)"]; 
    unset($a["December (3)"]); 
} 
//$a is a reference; this avoids accidental overwrites on the last subarray 
unset($a); 

可以再次循環數組,你就會有新的鍵:

foreach ($arr as $a) { 
    //do sth with $a["December"]; 
    //do sth with $a["Date"]; 
    //do sth with $a["Location & Event"]; 
} 
+0

太好了,謝謝!我已經使用你的和Mala的例子來實現我想要的... – Indigo 2010-07-05 01:39:08

0

事情是這樣的:

<?php 
$array = array(
    array(
     'date' => ..., 
     'location' => ..., 
     'event' => .... 
    ), 
    ... 
); 
?> 

2

你會想將這些值複製到一個新的數組中。你可以這樣做:

foreach ($arr as $a) 
{ 
    // this gets the keys 'December', 'December (2)', etc 
    $keys = array_keys($a) 

    // this copies the values to the new array 
    $newarr['date'] = $a[$keys[0]]; 
    $newarr['location'] = $a[$keys[1]]; 
    $newarr['event'] = $a[$keys[2]]; 
    // ... continue with as many fields as you have or need 
} 

然後可以通過$newarr[1]['date']等訪問每個元素。在「December(3)」等中使用array_keys()而不是硬編碼的結果是,無論哪個月,該函數都能正常工作(我假設您可能必須在1月,2月等時運行此功能。

坦率地說,不過,如果你不舒服的數組,你可能不應該試圖做數據庫的工作......

+0

真棒謝謝...是'十二月','十二月(2)'等將改變,所以不能被硬編碼... – Indigo 2010-07-05 01:40:33

0

假設鍵總是「月」,「十二月(2 )」等,應該採取重命名的護理:

foreach ($array as &$entry) { 
    $entry = array('Date' => $entry['December'], 'Location' => $entry['December (2)'], 'Event' => $entry['December (3)']); 
} 

在那裏,每個條目是在$array[0]['Date']訪問,$array[1]['Date']等。您可以在for循環中循環播放它們,並使用$array[$i]['Date'],或者使用另一個foreach循環。這是一個基本的練習,但我會留給你。