5

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?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
user3176519
  • 393
  • 1
  • 9
  • 16

2 Answers2

7

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
Rizier123
  • 58,877
  • 16
  • 101
  • 156
5

I like array_column() but if you don't have PHP >= 5.5.0:

$list = implode(',', array_map(function($v) { return $v[1]; }, $data['sales']));

Or with the foreach:

foreach ($data['sales'] as $row) {
    $list[] = $row[1];
}
$list = implode(',', $list);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • 1
    I think this would sounds better: *but if you don't have PHP >= 5.5.0*, [see my profile](http://stackoverflow.com/users/2844319/abracadaver). – Rizier123 Aug 11 '15 at 16:03