使用 Explode 为每个嵌套
Make nested for each Using Explode
我需要获取 key2 的数组值,而不是
key2: "value2-bonusValue"
我需要这样得到它
key2: {
"value2",
"bonusValue"
}
如果我删除了第二个:从一个数组中我得到未定义的偏移量:1 我需要能够获得没有键的数组和带有多键的键
$my_string = "key0:value0,key1:value1,key2:value2-bonusValue";
$convert_to_array = explode(',', $my_string);
foreach($convert_to_array as $_array){
$temp = explode(":", $_array);
$arrays[$temp[0]] = $temp[1];
}
return $arrays;
您只缺少一组,即子元素的拆分。在此代码中,它按 -
拆分值,但如果只有一个元素,则将其设置回第一个元素,否则将子数组添加到...
$convert_to_array = explode(',', $my_string);
foreach($convert_to_array as $_array){
$temp = explode(":", $_array);
$sub = explode("-", $temp[1]);
if ( count($sub) == 1 ) {
$sub = $sub[0];
}
$arrays[$temp[0]] = $sub;
}
print_r( $arrays );
给出...
Array
(
[key0] => value0
[key1] => value1
[key2] => Array
(
[0] => value2
[1] => bonusValue
)
)
对于缺失的 :
您可以检查 $temp
...
中的元素数量
$convert_to_array = explode(',', $my_string);
foreach($convert_to_array as $_array){
$temp = explode(":", $_array);
if ( count($temp) == 2 ) {
$sub = explode("-", $temp[1]);
if ( count($sub) == 1 ) {
$sub = $sub[0];
}
$arrays[$temp[0]] = $sub;
}
}
但不确定要如何处理该值。
我需要获取 key2 的数组值,而不是
key2: "value2-bonusValue"
我需要这样得到它
key2: {
"value2",
"bonusValue"
}
如果我删除了第二个:从一个数组中我得到未定义的偏移量:1 我需要能够获得没有键的数组和带有多键的键
$my_string = "key0:value0,key1:value1,key2:value2-bonusValue";
$convert_to_array = explode(',', $my_string);
foreach($convert_to_array as $_array){
$temp = explode(":", $_array);
$arrays[$temp[0]] = $temp[1];
}
return $arrays;
您只缺少一组,即子元素的拆分。在此代码中,它按 -
拆分值,但如果只有一个元素,则将其设置回第一个元素,否则将子数组添加到...
$convert_to_array = explode(',', $my_string);
foreach($convert_to_array as $_array){
$temp = explode(":", $_array);
$sub = explode("-", $temp[1]);
if ( count($sub) == 1 ) {
$sub = $sub[0];
}
$arrays[$temp[0]] = $sub;
}
print_r( $arrays );
给出...
Array
(
[key0] => value0
[key1] => value1
[key2] => Array
(
[0] => value2
[1] => bonusValue
)
)
对于缺失的 :
您可以检查 $temp
...
$convert_to_array = explode(',', $my_string);
foreach($convert_to_array as $_array){
$temp = explode(":", $_array);
if ( count($temp) == 2 ) {
$sub = explode("-", $temp[1]);
if ( count($sub) == 1 ) {
$sub = $sub[0];
}
$arrays[$temp[0]] = $sub;
}
}
但不确定要如何处理该值。