数组,从数组键中提取值并组合在一起

时间:2011-05-31 11:10:13

标签: php arrays multidimensional-array

使用Sencha Touch(对问题不重要),下面的数据数组将发送到我的PHP脚本。

["slider3"]     =>  1
["toggle3"]     =>  0
["text3"]       =>  "text"
["slider8"]     =>  5
["toggle8"]     =>  0
["text8"]       =>  "text"
["slider11"]    =>  4
["toggle11"]    =>  0
["text11"]      =>  "text"
["slider4"]     =>  1
["toggle4"]     =>  0
["text4"]       =>  "text"

正如您所看到的,在没有像(1 - > 2 - > 3)这样的逻辑标识符的意义上,Array有点“奇怪”。而是存在输入字段的名称(来自Sencha),其中添加了该字符串的数字。

您在密钥末尾看到的数字(3,8,11,4)是“数据”的实际ID。

这是我被卡住的地方。为了进一步处理数据,我想将接收到的数组修改为另一个数组,如:

[0]

    ["questionid"]  =>  3 (<- Number on the end of the original key)
    ["toggle"]      =>     value from toggle3
    ["slider"]      =>  value from slider3
    ["text"]        =>  value form text3

[1]

    ["questionid"]  =>  8 (<- Number on the end of the original key)
    ["toggle"]      =>  value from toggle8
    ["slider"]      =>  value from slider8
    ["text"]        =>  value from text8

etc.

或者换句话说,我想在KEY的末尾将具有相同ID的数据组合在一个新数组中。

任何人都知道如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

尝试:

<?php
$data = array(
    "slider3"     =>  1,
    "toggle3"     =>  0,
    "text3"       =>  "text",
    "slider8"     =>  5,
    "toggle8"     =>  0,
    "text8"       =>  "text",
    "slider11"    =>  4,
    "toggle11"    =>  0,
    "text11"      =>  "text",
    "slider4"     =>  1,
    "toggle4"     =>  0,
    "text4"       =>  "text",
);

$newData = array();
foreach ($data as $entryKey => $entry) {
    if (preg_match('/^(.+?)(\d+)$/', $entryKey, $matches)) {
        list(, $key, $id) = $matches;

        if (!isset($newData[$id])) {
            $newData[$id] = array(
                'questionid' => $id
            );
        }

        $newData[$id][$key] = $entry;
    }
}

$newData = array_values($newData);
print_r($newData);

<强>输出

Array
(
    [0] => Array
        (
            [questionid] => 3
            [slider] => 1
            [toggle] => 0
            [text] => text
        )

    [1] => Array
        (
            [questionid] => 8
            [slider] => 5
            [toggle] => 0
            [text] => text
        )

    [2] => Array
        (
            [questionid] => 11
            [slider] => 4
            [toggle] => 0
            [text] => text
        )

    [3] => Array
        (
            [questionid] => 4
            [slider] => 1
            [toggle] => 0
            [text] => text
        )

)