Patrioticcow
Patrioticcow

Reputation: 27038

php, how to grab data from an multidimensional array?

i have an array that looks like this:

foreach($obj as $key => $value)
{
print_r ($obj);
}

Array
(
[id] => 24991526504444
[name] => 21test
[picture] => http://profile.ak.fbcdn.net/hprofile-ak-sn4/276505_2499152255_s.jpg
[link] => http://apps.facebook.com/test/vote=6189373
[likes] => 1
[category] => Website
[parking] => Array
    (
        [street] => 0
        [lot] => 0
        [valet] => 0
    )

[payment_options] => Array
    (
        [cash_only] => 0
        [visa] => 0
        [amex] => 0
        [mastercard] => 0
        [discover] => 0
    )
)

how can i get the data from this array, for ex the id, or the likes.

i've tryed echo $key['likes'] or echo $key[$value['likes']] and some more combinations and it doesn't work

any ideas? thanks

Upvotes: 0

Views: 181

Answers (4)

Mateo Torres
Mateo Torres

Reputation: 1625

You are using foreach, that means you are iterating array elements, you should be using

    $obj['likes']

should return the value on the array (1 in your case).

And for the multidimensional ones

    $obj['payment_options']['cash_only']

should return the value (0 in your case)

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270607

According to this:

foreach($obj as $key => $value)
{
print_r ($obj);
}

the array you have displayed is actually the full structure of $obj and not any of its key=>value pairs.

So you should just need:

echo $obj['likes'];
echo $obj['id'];

Upvotes: 1

simshaun
simshaun

Reputation: 21466

Please read the manual on arrays.

You don't need a loop to access an array. What you want can be done simply with
$obj['id'] or $obj['likes'].

Upvotes: 1

user229044
user229044

Reputation: 239270

$key isn't your array, $obj is your array. You should be using $obj['likes'] or $obj['parking']['street']. You don't have to enumerate the keys to access the keys/values within the object, just use $obj.

Also, your foreach doesn't make sense:

foreach($obj as $key => $value)
{
    print_r ($obj);
}

This reads "For each key in the array, print the entire array". You don't have to loop at all, the whole purpose of print_r is to recursively print the contents of an array for you with no looping. Just use

print_r($obj);

Upvotes: 2

Related Questions