php - 无法从数组获取正确的值

原文 标签 php arrays for-loop multidimensional-array foreach

Not able to fetch correct value from array

I wish to fetch values from the following array

echo "<pre>";
print_r($attachments); 
echo "</pre>";


    Array
    (
        [0] => Array
            (
                [is_attachment] => 
                [filename] =>  Desert.jpg
                [name] =>  Desert.jpg
                [attachment] => 
            )

        [1] => Array
            (
                [is_attachment] => 1
                [filename] => Hydrangeas.jpg
                [name] =>  Hydrangeas.jpg
                [attachment] => 
            )
    )

I used this code to fetch the values

foreach($attachments as $value)
    { 
        foreach($value as $values)
            { 
                echo $values[filename];
                echo "<br>";
            } 
    }

O/P that i got is

D
D
H
H

The desired o/p should be

 Desert.jpg
 Hydrangeas.jpg

Can anyone tell where i went wrong

Answer

No need of two loops, you can get values from single loop as it's outer loop of [0],[1] etc.

foreach($attachments as $value)
    { 
        echo $value['filename'];
                echo "<br>"; 
    }

翻译

我希望从以下数组中获取值

echo "<pre>";
print_r($attachments); 
echo "</pre>";


    Array
    (
        [0] => Array
            (
                [is_attachment] => 
                [filename] =>  Desert.jpg
                [name] =>  Desert.jpg
                [attachment] => 
            )

        [1] => Array
            (
                [is_attachment] => 1
                [filename] => Hydrangeas.jpg
                [name] =>  Hydrangeas.jpg
                [attachment] => 
            )
    )


我用这段代码来获取值

foreach($attachments as $value)
    { 
        foreach($value as $values)
            { 
                echo $values[filename];
                echo "<br>";
            } 
    }


我得到的O / P是

D
D
H
H


所需的输出/输出应为

 Desert.jpg
 Hydrangeas.jpg


谁能说出我错了
最佳答案
不需要两个循环,您可以从单个循环获取值,因为它是[0],[1]等的外部循环。

foreach($attachments as $value)
    { 
        echo $value['filename'];
                echo "<br>"; 
    }
相关推荐

php - cakePHP在模型中使用请求/身份验证数据的3个最佳实践(基于帐户的云服务)

php - 什么数据类型可用于在mysql中放置标志(布尔值)?

javascript - 尝试将数据从.php文件传递到.js文件

php - 更改子菜单时如何更改网页背景?

php - Symfony2:如何避免数据库中已经存在重复的实体?

php - Eclipse中的PHP 7调试器设置

javascript - 访问URL参数-PHP和Angular.js

php - 使用更新的MySQL库修复PHP数据库连接失败

php - PHP代码不允许多个输入值通过我的表单发送

php - Laravel 5.1内部联接查询中的问题