$data
已
stdClass Object
(
[class] => srt-fields
[rules_field_1] => 1
[rules_condition_1] => 0
[rules_value_1] => text
[rules_field_2] => 3
[rules_condition_2] => 1
[rules_value_2] => another_text
...
)
现在我有另一个数组$newdata
,我需要索引$newdata['rules']
,以便它应该是这样的:
$newdata['rules'] => array(
[field] => 1,
[condition] => 0,
[value] => text
),
array(
[field]=> 3,
[condition] =>1,
[value] => another_text
),
...
谢谢!
答案 0 :(得分:1)
您可以像数组一样迭代对象的属性:
$newdata['rules']=[];
foreach ($data as $key => $value) {
if (substr($key,0,6)=='rules_') {
// split key using '_'
$parts = explode('_',$key);
// get the 'name'
$name = $parts[1] ;
// get the index (-1 to be 0 based)
$idx = $parts[2] - 1;
// store data in new array
$newdata['rules'][$idx][$name] = $value;
}
}
print_r($newdata);
输出:
Array
(
[rules] => Array
(
[0] => Array
(
[field] => 1
[condition] => 0
[value] => text
)
[1] => Array
(
[field] => 3
[condition] => 1
[value] => another_text
)
)
)
答案 1 :(得分:0)
这是工作代码,
$data = [
"class" => "srt-fields",
"rules_field_1" => "1",
"rules_condition_1" => "0",
"rules_value_1" => "text",
"rules_field_2" => "3",
"rules_condition_2" => "1",
"rules_value_2" => "another_text",
];
$result = [];
foreach ($data as $k => $v) {
$num = filter_var($k, FILTER_SANITIZE_NUMBER_INT);
if (!empty($num)) {
$result['rules'][$num][(str_replace(['rules_', '_'], '', preg_replace('/[0-9]+/', '', $k)))] = $v;
}
}
$result['rules'] = array_values($result['rules']);
print_r($result);
str_replace - 用替换字符串
替换所有出现的搜索字符串filter_var - 使用指定的过滤器过滤变量
preg_replace - 执行正则表达式搜索并替换
str_replace - 用替换字符串
替换所有出现的搜索字符串以下是demo。
答案 2 :(得分:0)
绝对不要为此任务使用正则表达式 - 因为它是不必要的资源开销。分解下划线上的键,并使用各个组件在输出数组中构建多级键。
代码:(Demo)
$data = (object)[
"class" => "srt-fields",
"rules_field_1" => "1",
"rules_condition_1" => "0",
"rules_value_1" => "text",
"rules_field_2" => "3",
"rules_condition_2" => "1",
"rules_value_2" => "another_text"
];
foreach ($data as $key => $value) {
$bits = explode('_',$key); // this will produce a 1-element array from `class` and a 3-element array from others
if (isset($bits[2])) { // if element [2] exists, then process the qualifying data
$newdata[$bits[0]][$bits[2]-1][$bits[1]] = $value;
// ^^- make zero based
}
}
var_export($newdata);
输出:
array (
'rules' =>
array (
0 =>
array (
'field' => '1',
'condition' => '0',
'value' => 'text',
),
1 =>
array (
'field' => '3',
'condition' => '1',
'value' => 'another_text',
),
),
)
我使用-1
使输出键类似于从零开始/索引的数组。如果您的字段可能没有连续排序,则可以删除-1
并在循环后写入$newdata['rules'] = array_values($newdata['rules']);
。
答案 3 :(得分:-1)
pageIndex
您可以尝试使用此代码。请忽略语法错误,因为我没有尝试过这段代码,但它应该会给你结果。