如何从子数组中获取所有文件名并计数?

时间:2018-08-23 02:00:42

标签: php arrays multidimensional-array

我有一个名为$thumbs_meta的以下数组,我想从sizes子数组中获取所有文件名,以便我可以对它们进行计数并将它们粘贴到一个逗号分隔的字符串中。

Array
(
    [width] => 1024
    [height] => 768
    [file] => 2018/08/Penguins.jpg
    [sizes] => Array
        (
            [thumbnail] => Array
                (
                    [file] => Penguins-150x150.jpg
                    [width] => 150
                    [height] => 150
                    [mime-type] => image/jpeg
                )

            [medium] => Array
                (
                    [file] => Penguins-300x225.jpg
                    [width] => 300
                    [height] => 225
                    [mime-type] => image/jpeg
                )

            [medium_large] => Array
                (
                    [file] => Penguins-768x576.jpg
                    [width] => 768
                    [height] => 576
                    [mime-type] => image/jpeg
                )

            [large] => Array
                (
                    [file] => Penguins-1024x768.jpg
                    [width] => 1024
                    [height] => 768
                    [mime-type] => image/jpeg
                )

            [twentyseventeen-thumbnail-avatar] => Array
                (
                    [file] => Penguins-100x100.jpg
                    [width] => 100
                    [height] => 100
                    [mime-type] => image/jpeg
                )

        )
)

我尝试过foreach,但是又走了一步,所以不起作用。我应该循环两次吗?

这是我目前无法使用的foreach:

foreach($thumbs_meta as $key => $value) {
        $fullname .=$value['file'].',';

                            }
     $thumbs_count = count( $thumbs_meta );

具体来说,我想从以下键中隔离file值:thumbnailmediumlargemedium_largetwentyseventeen-thumbnail-avatar

我的预期数量为5

我的逗号分隔字符串为:

Penguins-150x150.jpg,Penguins-300x225.jpg,Penguins-768x576.jpg,Penguins-1024x768.jpg,Penguins-100x100.jpg

1 个答案:

答案 0 :(得分:1)

$thumbnail_files = array_column($thumbs_meta['sizes'], 'file'); var_export($thumbnail_files); echo "\nCount: " , count($thumbnail_files) , "\n\n"; echo "Imploded: " , implode(',', $thumbnail_files); 子数组上的

source code将以非常简洁和易读的方式满足您的需求。

代码:(array_column()

array (
  0 => 'Penguins-150x150.jpg',
  1 => 'Penguins-300x225.jpg',
  2 => 'Penguins-768x576.jpg',
  3 => 'Penguins-1024x768.jpg',
  4 => 'Penguins-100x100.jpg',
)
Count: 5

Imploded: Penguins-150x150.jpg,Penguins-300x225.jpg,Penguins-768x576.jpg,Penguins-1024x768.jpg,Penguins-100x100.jpg

输出:

UriBuilder.fromUri("https://www.google.co.nz/search?q=test").replaceQuery(null).build();