dqrq93879 2017-12-30 11:01
浏览 41
已采纳

如何在数组中提取元素,而数组又在几个数组中,并使用foreach循环显示它

I have a result of a query, which is the name of the image. I am storing the image names for every image Id in an array. Now, on the view page I am using foreach loop to display these images. The problem is I can't extract the elements(the name of the images) from this array.

My array is

Array ( [0] => Array ( [0] => Array ( [picture] => 5a3a13f237715637629.jpeg ) ) [1] => Array ( [0] => Array ( [picture] => 5a3b602654cfd527057.jpg ) ) )

I have used print_r and got this, now I want to extract only the 5a3a13f237715637629.jpeg values and display these using foreach loop on the view page. Any help is welcome.

  • 写回答

1条回答 默认 最新

  • douhuanqiao5290 2017-12-30 13:16
    关注

    The simplest way I can think of would be to json the array and then use regex to extract the filenames. You are then left with an array of filenames to loop through and display:

    preg_match('/\w+.jpeg/', json_encode($array), $matches);
    
    print_r($matches);
    

    The benefits of doing it this way are that you don't need to know the structure of the array or go through embedded looping to find the values.

    If you want do want the loop way; try this:

    $array = array(
        1 => array(
            'picture' => '5a3a13f237715637629.jpeg'    
        ),
        2 => array(
            'picture' => 'fnofweofweiofniewof.jpeg'    
        )
    );
    
    print_r(search_r($array, 'picture', $results));
    
    function search_r($array, $key, &$results) {
    
        if (!is_array($array)) {
            return;
        }
    
        if (isset($array[$key])) {
            $results[] = $array[$key];
        }
    
        foreach ($array as $subarray) {
            search_r($subarray, $key, $results);
        }
    
        return $results;
    }
    

    That will result:

    Array
    (
        [0] => 5a3a13f237715637629.jpeg
        [1] => fnofweofweiofniewof.jpeg
    )
    

    PS. This is an adaption of this answer

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧