如何从这个多维 PHP 数组中获取单个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4383914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:53:49  来源:igfitidea点击:

How to get single value from this multi-dimensional PHP array

phparrays

提问by wow

Example print_r($myarray)

例子 print_r($myarray)

Array
(
    [0] => Array
    (
        [id] => 6578765
        [name] => John Smith
        [first_name] => John
        [last_name] => Smith
        [link] => http://www.example.com
        [gender] => male
        [email] => [email protected]
        [timezone] => 8
        [updated_time] => 2010-12-07T21:02:21+0000
    )
)

Question, how to get the $myarrayin single value like:

问题,如何获得$myarray单个值,如:

echo $myarray['email'];  will show [email protected]

回答by Dan Grossman

Look at the keys and indentation in your print_r:

查看您的 中的键和缩进print_r

echo $myarray[0]['email'];

echo $myarray[0]['gender'];

...etc

...等等

回答by Virendra Yadav

Use array_shiftfunction

使用array_shift功能

$myarray = array_shift($myarray);

This will move array elements one level up and you can access any array element without using [0]key

这会将数组元素向上移动一级,您可以在不使用[0]键的情况下访问任何数组元素

echo $myarray['email'];  

will show [email protected]

将显示 [email protected]

回答by Mike Axiak

I think you want this:

我想你想要这个:

foreach ($myarray as $key => $value) {
    echo "$key = $value\n";
}

回答by Francesco Casula

You can also use array_column(). It's available from PHP 5.5: php.net/manual/en/function.array-column.php

您也可以使用array_column(). 它可以从 PHP 5.5 获得:php.net/manual/en/function.array-column.php

It returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.

它从数组的单个列中返回值,由 column_key 标识。或者,您可以提供一个 index_key 以通过输入数组中 index_key 列中的值对返回数组中的值进行索引。

print_r(array_column($myarray, 'email'));

回答by Masad Ashraf

echo $myarray[0]->['email'];

Try this only if it you are passing the stdclass object

仅当您通过时才尝试此操作 stdclass object

回答by v64

The first element of $myarrayis the array of values you want. So, right now,

的第一个元素$myarray是您想要的值数组。所以,现在,

echo $myarray[0]['email']; // This outputs '[email protected]'

If you want that array to become $myarray, then you just have to do

如果您希望该数组成为$myarray,那么您只需要做

$myarray = $myarray[0];

Now, $myarray['email']etc. will output as expected.

现在,$myarray['email']等将按预期输出。