-4

我有这个数组

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

我使用带有@@的explode 函数来explode this。我得到这样的数组..

[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
                        )    
                )    
        )    
)
4

2 回答 2

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);
于 2012-09-25T08:59:11.190 回答
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];
}
于 2012-09-25T08:57:10.220 回答