gpt4 book ai didi

php字符串转数组结构

转载 作者:行者123 更新时间:2023-12-04 10:42:02 25 4
gpt4 key购买 nike

在 php 中,我需要转换这个数组:

array(
'group1_selector1_rule1' => value
, 'group1_selector1_rule2' => value
, 'group1_selector1_rule3' => value
, 'group1_selector2_rule1' => value
, 'group1_selector2_rule2' => value
, 'group2_selector1_rule1' => value
, 'group2_selector1_rule2' => value
, 'group3_selector1_rule1' => value
, 'group3_selector2_rule1' => value
, 'group3_selector2_rule2' => value
);

进入这个:

array(
'group1' => array(

'selector1' => array(
'rule1' => value
, 'rule2' => value
, 'rule3' => value
)

, 'selector2' => array(
'rule1' => value
, 'rule2' => value
)

) // end group 1

, 'group2' => array(

'selector1' => array(
'rule1' => value
, 'rule2' => value
)
) // end group 2

, 'group3' => array(

'selector1' => array(
'rule1' => value
)

, 'selector2' => array(
'rule1' => value
, 'rule2' => value
)
) // end group 3
); // end array

如果有人想提出一个聪明的方法,我会很感兴趣:)我想我可以使用一些算法,但我想要一些优雅的东西,并且觉得巧妙地使用 explode() 和一些“array_merging”函数可以做到这一点?

最佳答案

  $res_array = array();
foreach ($array as $key=>$value) {
$x = explode("_", $key);
$res_array[$x[0]][$x[1]][$x[2]] = $value;
}

var_dump($res_array);

对于$数组

$array = array(
'group1_selector1_rule1' => 'value1'
, 'group1_selector1_rule2' => 'value2'
, 'group1_selector1_rule3' => 'value3'
, 'group1_selector2_rule1' => 'value4'
, 'group1_selector2_rule2' => 'value5'
, 'group2_selector1_rule1' => 'value6'
, 'group2_selector1_rule2' => 'value7'
, 'group3_selector1_rule1' => 'value8'
, 'group3_selector2_rule1' => 'value9'
, 'group3_selector2_rule2' => 'value10'
);

输出:

array(3) {
["group1"]=>
array(2) {
["selector1"]=>
array(3) {
["rule1"]=>
string(6) "value1"
["rule2"]=>
string(6) "value2"
["rule3"]=>
string(6) "value3"
}
["selector2"]=>
array(2) {
["rule1"]=>
string(6) "value4"
["rule2"]=>
string(6) "value5"
}
}
["group2"]=>
array(1) {
["selector1"]=>
array(2) {
["rule1"]=>
string(6) "value6"
["rule2"]=>
string(6) "value7"
}
}
["group3"]=>
array(2) {
["selector1"]=>
array(1) {
["rule1"]=>
string(6) "value8"
}
["selector2"]=>
array(2) {
["rule1"]=>
string(6) "value9"
["rule2"]=>
string(7) "value10"
}
}
}

关于php字符串转数组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5641833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com