Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 329
davey Avatar asked Apr 26 '26 02:04

davey


1 Answers

foreach ($_POST['prod_prop'] as $prop_ids) {
    $list = join(',', array_map(
        function ($id) { return current(explode('|', $id)); },
        $prop_ids
    ));    
    echo $list;
}
like image 60
deceze Avatar answered Apr 27 '26 19:04

deceze