转换为关联数组 PHP

Convert to associative array 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

数据上的数字是索引。你怎么能把它放在关联数组中?我想知道与该数据关联数组的示例。谢谢

可以用explode() and foreach

完成

步骤:

1) 首先用换行符分解字符串 \n.

2) 看看它。

3) 你会得到单独的行,用 =.

explode() 它

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
)

可以通过将字符串转换为 query string 格式然后使用 parse_str() 来完成 必须插入 1.0 => Books (append.0) 和 1.2.0 => 艺术、电影和摄影(附加 .0)

</p> <pre><code> $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
                )

        )

)