Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

php - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...