开发者

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

开发者 https://www.devze.com 2023-01-29 15:21 出处:网络
This question already has answers here: 开发者_运维知识库 How can I access an array/object? (6 answers)
This question already has answers here: 开发者_运维知识库 How can I access an array/object? (6 answers) Closed 7 months ago.

Example 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@example.com
        [timezone] => 8
        [updated_time] => 2010-12-07T21:02:21+0000
    )
)

Question, how to get the $myarray in single value like:

echo $myarray['email'];  will show email@example.com


Look at the keys and indentation in your print_r:

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

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

...etc


Use array_shift function

$myarray = array_shift($myarray);

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

echo $myarray['email'];

will show email@example.com


I think you want this:

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


You can also use array_column(). It's available from 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.

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


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

Try this only if it you are passing the stdclass object


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

echo $myarray[0]['email']; // This outputs 'email@example.com'

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

$myarray = $myarray[0];

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

0

精彩评论

暂无评论...
验证码 换一张
取 消