PHP多维数组获取逗号分隔的字符串值

时间:2015-03-11 12:52:28

标签: php arrays multidimensional-array

我有以下数组结构:

[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
                )

        )

我想循环遍历每个父编号并输出逗号分隔的第二级数组第一部分的字符串

那么,我怎样才能得到每个数字的sting分隔值,所以期望的结果如下:

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 |长,129 | 3 |中长131 | 3 |,130 | 3 |长,129 | 3 |中长< / p>

5 个答案:

答案 0 :(得分:1)

foreach ($_POST['prod_prop'] as $prop_ids) {
    $list = join(',', array_map(
        function ($id) { return current(explode('|', $id)); },
        $prop_ids
    ));    
    echo $list;
}

答案 1 :(得分:0)

您可以使用以下功能对其进行归档: - 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,",").",";
}


        }

亲自试试。希望这可以帮到你。

答案 2 :(得分:0)

为什么不滚动数组,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中的正则表达式的语法。在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>

答案 3 :(得分:0)

这听起来像是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;
}

答案 4 :(得分:-1)

> $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***
相关问题