提问人:Hida 提问时间:5/9/2023 最后编辑:Hida 更新时间:5/9/2023 访问量:45
Php 将文本解析为包含重复键的数组
Php Parse text to array with contain duplicate key
问:
我想将文本解析为数组:
用 =>
分隔的文本 首先是键,最后一个是值
我将文本解析为数组。如果找到重复的键,则该值是包含这些键的数组。如果不是,则该值为字符串。
预期结果如下所示:
Array
(
[phone] => phone1
[email] => Array
(
[0] => email1
[1] => email2
[2] => email3
[3] => email4
)
[fax] => fax1
[other] => Array
(
[0] => other1
[1] => other2
[2] => other3
)
)
我的脚本不起作用
<pre>
<?php
$txt = "
phone=>phone1
email=>email1
email=>email2
fax=>fax1
email=>email3
other=>other
other=>other1
email=>email4
other=>other
";
$lns = explode("\n", $txt);
print_r($lns);
$res = array();
foreach($lns as $v) {
$trim = trim($v);
if($trim != '') {
list($extName, $extVal) = explode("=>", $v);
if(array_key_exists($extName, $res)) {
//echo "eee=$extName, $extVal\n";
$vv[] = $extVal;
$value = $vv;
} else {
//echo "nnn=$extName, $extVal\n";
$value = $extVal;
}
$res[$extName] = $value;
}
}
print_r($res);
?>
</pre>
我只是得到意想不到的结果:
Array
(
[ phone] => phone1
[ email] => Array
(
[0] => email2
[1] => email3
[2] => other1
[3] => email4
)
[ fax] => fax1
[ other] => Array
(
[0] => email2
[1] => email3
[2] => other1
[3] => email4
[4] => other
)
)
答:
2赞
Hida
5/9/2023
#1
所以我通过为键和值创建数组来解决这个问题。 然后使用 array_unique() 和 array_keys() 函数。
$txt = "
phone=>phone1
email=>email1
email=>email2
fax=>fax1
email=>email3
other=>other
other=>other1
email=>email4
other=>other
";
$rowsArr = explode("\n", $txt);
foreach($rowsArr as $row) {
$trim = trim($row);
if($trim != '') {
list($k, $v) = explode("=>", $row);
$arr_keys[] = trim($k);
$arr_vals[] = trim($v);
}
}
$uniqueKeys = array_unique($arr_keys);
foreach($uniqueKeys as $uniqueKey) {
$arr_keycheck = array_keys($arr_keys, $uniqueKey);
if(count($arr_keycheck)>1) {
$value = array();
foreach($arr_keycheck as $keyval) {
$value[] = $arr_vals[$keyval];
}
} else {
$value = $arr_vals[$arr_keycheck[0]];
}
$result[$uniqueKey] = $value;
}
print_r($result);
结果如下:
Array
(
[phone] => phone1
[email] => Array
(
[0] => email1
[1] => email2
[2] => email3
[3] => email4
)
[fax] => fax1
[other] => Array
(
[0] => other
[1] => other1
[2] => other
)
)
上一个:从响应中获取数组中的元素
评论
$vv
未定义。也许在行之前添加$vv = is_array($res[$extName]) ? $res[$extName] : [$res[$extName]];
$vv[] = $extVal;
explode
explode("=>", $trim);