使用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"
正如您所看到的,Array有点"奇怪",因为它没有像(1->2->3)这样的逻辑标识符。取而代之的是输入字段的名称(来自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的数据分组到一个新的数组中。
有人知道如何解决这个问题吗?
尝试:
<?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
)
)