将某些子数组转换为另一个数组

时间:2014-10-07 08:29:04

标签: php arrays multidimensional-array

我正在通过jQuery收集页面上的所有表单字段,然后将它们传递到ajax帖子中的php页面,该数组传递如下(实际数据目前超过60个字段/数组)

Array
(
    [0] => Array
        (
            [0] => main
            [1] => text
            [2] => product-name
            [3] => fieldvalue
        )
[1] => Array
    (
        [0] => main
        [1] => select
        [2] => product-range
        [3] => fieldvalue
    )

[2] => Array
    (
        [0] => main
        [1] => select
        [2] => product-year
        [3] => fieldvalue
    )

[3] => Array
    (
        [0] => main
        [1] => text
        [2] => product-type
        [3] => fieldvalue
    )

[4] => Array
    (
        [0] => main
        [1] => text
        [2] => product-sku
        [3] => fieldvalue
    )

[5] => Array
    (
        [0] => main
        [1] => text
        [2] => component-name
        [3] => fieldvalue
    )

[6] => Array
    (
        [0] => main
        [1] => text
        [2] => component-stid
        [3] => fieldvalue
    )

在表单上,​​用户可以动态添加多组组件字段,我要做的是将7个组件字段组合成一个数组,然后添加到一个多维数组的组件中,我可以稍后对其进行排序。我目前循环遍历数组数据的方式如下

foreach($formdata as $value) {

        if($value[0] == 'main') {

            if($value[2] == 'product-name') { $productname = $value[3]; }
            if($value[2] == 'product-range') { $productrange = $value[3]; }
            if($value[2] == 'product-year') { $productyear = $value[3]; }
                    }
}

我真的很难找到一种干净利落的方法,有人可以就最佳做法提出建议吗?

由于

1 个答案:

答案 0 :(得分:1)

您可以使用这样的关联数组:

$arr = array(
    'product_range' => array("main" => "text", 'product_range' => 'val'),
    'product_type' => array("main" => "text", 'product_type' => 'val')
);
foreach ($arr as $key => $val) {
    echo $key." is ".$val[$key]."<br>";
}