0

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

1
  • I don't think you understand how a foreach loop works... Commented Sep 13, 2011 at 18:23

4 Answers 4

2

$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);
Sign up to request clarification or add additional context in comments.

Comments

1

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'].

Comments

1

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'];

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.