[英]PHP multi dimensional array get comma separated string value
我有以下数组结构:
[prod_prop] => Array
(
[45375] => Array
(
[0] => 129|3|Mid-length
)
[45374] => Array
(
[0] => 130|3|Long
[1] => 129|3|Mid-length
)
[45373] => Array
(
[0] => 131|3|
[1] => 130|3|Long
[2] => 129|3|Mid-length
)
)
我想遍历第二级数组第一部分的每个父编号和 output 逗号分隔字符串
那么,我怎样才能得到每个数字的字符串分隔值,所以所需的结果如下:
45375 -> 返回 129
45374 -> 返回 130,129
45373 -> 返回 131,130,129
这是我当前的代码,它返回逗号分隔数组中的所有内容,而不是我之后的内容:
foreach($_POST['prod_prop'] AS $prop_ids) {
$list = implode(",",$prop_ids);
echo $list;
}
返回:131|3|131|3|,130|3|Long131|3|,130|3|Long,129|3|中长 131|3|,130|3|Long,129|3|Mid-长度
foreach ($_POST['prod_prop'] as $prop_ids) {
$list = join(',', array_map(
function ($id) { return current(explode('|', $id)); },
$prop_ids
));
echo $list;
}
您可以使用以下功能对其进行存档: end()
, explode()
, trim().
使用下面的代码
$last = end($_POST['prod_prop']);
foreach($_POST['prod_prop'] AS $prop_ids) {
foreach($prop_ids as $s){
$list .= ",".explode("|",$s)[0];
}
if($prop_ids==$last){
echo trim($list,",")."";
}
else{
echo trim($list,",").",";
}
}
自己尝试。希望对您有帮助。
为什么不滚动数组,将其值implode()
并在其上应用正则表达式?
$res = Array();
foreach($_POST["prod_prop"] as $bID=>$bLists) {
$str = implode(",", $bLists); // get list of values comma separated
preg_match_all("/(^|,)(\d+)/", $str, $m); //get all digits, which follow string start or comma
if (Count($m[1])) { // if value found - store it in $res array
$res[$bID] = implode(",", $m[1]);
}
}
一个注意事项:我不确定PHP中的regex语法。 在javascript中,以下作品
var str = "131|3|,130|3|Long,129|3|Mid-length"; $('#result').html(str.match(/(^|,)(\\d+)/g));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span id="result"></span>
这听起来像是array_reduce
一个好用例。 尝试这个:
foreach($_POST['prod_prop'] as $id => $properties) {
$result = array_reduce($properties, function($val, $item) {
return $val . ',' . substr($item, 0, strpos($item, '|'));
});
echo $result;
}
在每个子数组上使用strtok()
调用的迭代调用来隔离第一个 pipe 之前的 substring,然后在回显之前implode()
截断的元素。
foreach ($_POST['prod_prop'] as $prop_ids) {
echo implode(',', array_map(fn($v) => strtok($v, '|'), $prop_ids)) . '<br>';
}
> $stateId = Array (
> [0] => Array
> (
> [id] => 9
> [state_id] => 81
> [rto_id] => 82
> [is_active] => 1
> )
> [1] => Array
> (
> [id] => 10
> [state_id] => 82
> [rto_id] => 83
> [is_active] => 1
> )
>
> );
>
> $stateIds = implode(",", array_column($stateId, "state_id"));
>
> echo $stateIds;
>
>
> ***Result : 81,82***
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.