如果您有这些数据:
1=Books
1.1=Action & Adventure
1.2=Arts, Film & Photography
1.2.1=Architecture
1.2.2=Cinema & Broadcast
1.2.3=Dance
数据上的数字是索引。你怎么能把它放在关联数组中?我想知道一个带有该数据的关联数组的例子。感谢
答案 0 :(得分:3)
<强>步骤:强>
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)
可以通过将字符串转换为query string
格式然后使用parse_str()来完成
必须插入1.0 =&gt;书籍(append.0)
和1.2.0 =&gt;艺术,电影和摄影(追加.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);
$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 ) ) )