如何在php和smarty中制作多维数组

时间:2012-09-25 08:46:09

标签: php multidimensional-array

我有这个数组

 $a = array("008_@@_1_@@_Interieur_@@_1_@@_Inner-Bags",  "008_@@_1_@@_Interieur_@@_2_@@_Color", "008_@@_1_@@_Interieur_@@_3_@@_Material");`

我使用爆炸功能与 @@ 爆炸。我得到这样的数组..

[0] => 008 
[1] => 1 
[2] => Interieur
[3] => 1 
[4] => Inner-Bags 

等等。

所以我想要格式化数组的类型。

array('008' => array( '1' => array('Interieur' => array('1' => 'Inner-Bags', '2' => 'Color', '3' => 'Material'))));

这是我的逻辑......

<?php
$a = array("008_@@_1_@@_Interieur_@@_1_@@_Inner-Bags", "008_@@_1_@@_Interieur_@@_2_@@_Color", "008_@@_1_@@_Interieur_@@_3_@@_Material");
$i = 0;
echo '<pre>';
$innerD = array();
foreach($a as $key => $val) {
 $innerA = array();
 $a_exploded = explode("_@@_", $a[$key]);
 $innerA[$a_exploded[3]] = $a_exploded[4];
}

foreach($a as $key => $val) {
    //print_r($a[$key]);
 $innerB = array();
 $innerC = array();
 $a_exploded = explode("_@@_", $a[$key]);

// print_r($innerA);

 $innerB[$a_exploded[2]] = $innerA;
 $innerC[$a_exploded[1]] = $innerB;
 $innerD[$a_exploded[0]] = $innerC;
}
print_r($innerD);
?>

我已经使用了我的逻辑,但我没有得到像这样的正确数组..

Array
(
    [008] => Array
        (
            [1] => Array
                (
                    [Interieur] => Array
                        (
                            [3] => Material
                        )
                )    
        )    
)

我希望像这样对这种格式进行排列..

Array
(
    [008] => Array
        (
            [1] => Array
                (
                    [Interieur] => Array
                        (
                              [1] => Inner-Bags
                              [2] => Material
                              [3] => Color
                        )    
                )    
        )    
)

2 个答案:

答案 0 :(得分:2)

试试这个

$a = array("008_@@_1_@@_Interieur_@@_1_@@_Inner-Bags", "008_@@_1_@@_Interieur_@@_2_@@_Color", "008_@@_1_@@_Interieur_@@_3_@@_Material");
$i = 0;
echo '<pre>';
$innerD = array();
foreach($a as $val){
  $a_exploded = explode("_@@_", $val);
  $innerD[$a_exploded[0]][$a_exploded[1]][$a_exploded[2]][] = $a_exploded[3];
}
print_r($innerD);

答案 1 :(得分:1)

因为您在第一个foreach内重置了数组。

更改

foreach($a as $key => $val) {
    $innerA = array(); // <-- it is wrong string. remove it.
    $a_exploded = explode("_@@_", $a[$key]);
    $innerA[$a_exploded[3]] = $a_exploded[4];
}

为:

foreach($a as $key => $val) {
    $a_exploded = explode("_@@_", $a[$key]);
    $innerA[$a_exploded[3]] = $a_exploded[4];
}