davey
davey

Reputation: 1564

PHP multi dimensional array get comma separated string value

I have the following array structure:

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

        )

I want to loop through each parent number and output comma separated string of first part of second level array

So, how can I get a sting separated value for each number so desired result is as follows:

45375 -> returns 129

45374 -> returns 130,129

45373 -> returns 131,130,129

This is my current code which returns everything in the comma separated array not what im after:

 foreach($_POST['prod_prop'] AS $prop_ids) {
            $list = implode(",",$prop_ids);    
            echo $list;
        }

Returns: 131|3|131|3|,130|3|Long131|3|,130|3|Long,129|3|Mid-length 131|3|,130|3|Long,129|3|Mid-length

Upvotes: 3

Views: 4284

Answers (6)

mickmackusa
mickmackusa

Reputation: 47874

Use iterated calls of strtok() calls on each subarray to isolate the substring before the first pipe, then implode() the truncated elements before echoing.

foreach ($_POST['prod_prop'] as $prop_ids) {
    echo implode(',', array_map(fn($v) => strtok($v, '|'), $prop_ids)) . '<br>';
}

Upvotes: 0

Abhishek Gupta
Abhishek Gupta

Reputation: 51

> $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***

Upvotes: -1

deceze
deceze

Reputation: 522005

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

Upvotes: 2

dcarrith
dcarrith

Reputation: 7920

This sounds like a good use-case for array_reduce. Try this:

foreach($_POST['prod_prop'] as $id => $properties) {

    $result = array_reduce($properties, function($val, $item) {

        return $val . ',' . substr($item, 0, strpos($item, '|'));
    });

    echo $result;
}

Upvotes: 0

cyadvert
cyadvert

Reputation: 875

Why don't you scroll through array, implode() its values, and apply regex onto it?

$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]);
   }
}

One note: I'm not sure about syntax of regex in PHP. In javascript the following works

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>

Upvotes: 0

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

You can archive this with using these functions:- end(),explode(),trim(). Use the code below

$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,",").",";
}


        }

Try it for yourself.Hope this helps you.

Upvotes: 0

Related Questions