Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implode() only one column from a multidimensional array?

I have array in following format:

Array
(
    [sales] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => 6
                )

            [1] => Array
                (
                    [0] => 2
                    [1] => 8
                )

            [2] => Array
                (
                    [0] => 3
                    [1] => 25
                )

            [3] => Array
                (
                    [0] => 4
                    [1] => 34
                )

        )

)

Using:

foreach ($data['sales'] as $k => $row) {
    $list = implode(",",$row);
}

I get the following as output:

1,62,83,254,34

But I only need the second values from each subArray. The expected result needs to be:

6,8,25,34

How can I remove the first set of values?

like image 534
user3176519 Avatar asked Aug 11 '15 15:08

user3176519


People also ask

How do you implode a multidimensional array?

You could create a temporary array with the required values, then implode the contents. $deviceIds = array(); foreach ($multiDimArray as $item) { $deviceIds[] = $item['device_id']; } $str = implode(',', $deviceIds);

How do you implode an array?

If we have an array of elements, we can use the implode() function to join them all to form one string. We basically join array elements with a string. Just like join() function , implode() function also returns a string formed from the elements of an array.

How we can convert a multidimensional array to string without any loop?

Maybe in case you need to convert a multidimensional array into a string, you may want to use the print_r() function. This is also called “array with keys”. By adding “true” as its second parameter, all the contents of the array will be cast into the string.

How does array_ column work?

array_column() returns the values from a single column of the array , identified by the column_key . Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.


1 Answers

Just grab the first column from your array with array_column(), so that you end up with an array, e.g.

Array (
    [0] => 6
    [1] => 8
    [2] => 25
    [3] => 34
)

And implode() it then as you already did, e.g.

echo implode(",", array_column($data["sales"], 1));

output:

6,8,25,34
like image 169
Rizier123 Avatar answered Nov 14 '22 21:11

Rizier123