如果你有這樣的數據:轉換爲關聯數組PHP
1=Books
1.1=Action & Adventure
1.2=Arts, Film & Photography
1.2.1=Architecture
1.2.2=Cinema & Broadcast
1.2.3=Dance
上的數據的數量指標。你怎麼能把它放在關聯數組中?我想知道關聯數組的一個例子。由於
如果你有這樣的數據:轉換爲關聯數組PHP
1=Books
1.1=Action & Adventure
1.2=Arts, Film & Photography
1.2.1=Architecture
1.2.2=Cinema & Broadcast
1.2.3=Dance
上的數據的數量指標。你怎麼能把它放在關聯數組中?我想知道關聯數組的一個例子。由於
步驟來完成:
1)首先用爆炸換行字符\n
的字符串。
2)在它上面。
3)你會得到單獨的行,用=
爆炸()它。
4)您將得到所需的密鑰0
和價值1
。
5)將它作爲鍵值對存儲在數組中。 完成
$str = '1=Books
1.1=Action & Adventure
1.2=Arts, Film & Photography
1.2.1=Architecture
1.2.2=Cinema & Broadcast
1.2.3=Dance';
$arr = explode("\n", $str);
$assoc = array();
if (! empty($arr)) {
foreach ($arr as $k => $v) {
$temp = explode('=', $v);
$assoc[$temp[0]] = $temp[1];
}
}
echo '<pre>';print_r($assoc);echo '</pre>';
輸出:
Array
(
[1] => Books
[1.1] => Action & Adventure
[1.2] => Arts, Film & Photography
[1.2.1] => Architecture
[1.2.2] => Cinema & Broadcast
[1.2.3] => Dance
)
1.1,1.2,1.2.1,1.2.2,1.2.3如何在1中,我的意思是在書籍裏面?謝謝 –
它將以通常的方式工作。所提供的代碼能夠這樣做。 – Pupil
沒關係,如果你沒有這個代碼,我只想看看輸出。 –
可以通過將串進行成query string
格式,然後使用parse_str() 必須插入1.0 =>圖書(append.0) 和1.2 .0 =>藝術,電影&攝影(追加.0)
$str = '1.0=Books
1.1=Action & Adventure
1.2.0=Arts, Film & Photography
1.2.1=Architecture
1.2.2=Cinema & Broadcast
1.2.3=Dance';<br />
//replace & with and because parse_str not work with '&'
$str = str_replace('&','and',$str);
$str_ar = explode("\n",$str);
foreach($str_ar as $line){
$aar .= 'a';
$line_ar = explode('=',$line);
$array_index = explode('.',$line_ar[0]);
foreach($array_index as $index){
$aar .= '['.$index.']';
}
$aar.='='.($line_ar[1]).'&';
}
$aar = rtrim($aar,'&');
parse_str($aar,$o);
$o=array_shift($o);
輸出
Array ( [1] => Array ( [0] => Books [1] => Action and Adventure [2] => Array ( [0] => Arts, Film and Photography [1] => Architecture [2] => Cinema and Broadcast [3] => Dance ) ) )
非常感謝。我會研究你的代碼 –
爆炸上'='使LHS索引和RHS值 –
該數組的任何深度? – mitkosoft
是的。我想查看關聯數組,只需評論您的答案,以便我可以將我將對其他數據做的圖像成像。謝謝。 –