Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
echo $merchant_pic['shop']['campaign'];

I know that would give me the value of campaign. But first I have to know what is the first layer of the array - which is shop.

Problem is: the first layer could be anything.

Is there a way to get the value of second layer of array without knowing/defining what the first layer would be?

share|improve this question
2  
The question should be subjected to str_replace('layer','key',$stackquestion); –  Shankar Damodaran 2 hours ago
add comment

2 Answers

If you don't know the key of the target item inside $merchant_pic then you have to know its position relative to its siblings (is it the first item? the last? the third?).

If that is the only (or the first) item inside $merchant_pic then one way to get it easily is reset($merchant_pic), so you would write

echo reset($merchant_pic)['campaign']; // requires PHP >= 5.4
share|improve this answer
 
Smart answer, but I'm still wondering whether it is sane to process anything that is essentially undefined with a computer. –  Tibo 2 hours ago
 
@Tibo: It's not like that. It's quite common to get an array whose indexes mean nothing to you and you don't care about from some function (e.g. a list of user objects indexed by id). Imagine that you are only interested in the first user in the list. You don't know the key (id), but you also don't care. –  Jon 2 hours ago
 
I don't think this would work without hardcodding, if 2 or more first layers has key named campaign –  Royal Bg 1 hour ago
 
@RoyalBg: That would be a different question entirely -- one easily solved with a plain foreach. –  Jon 1 hour ago
add comment

You can loop through the keys until find one

<?php
$merchant_pic['not_shop'] = array(
    'rrr' => 'aaa',
    2 => 'a',
    'foo' => 'bar'
);
$merchant_pic['shop'] = array(
    'bla' => 1,
    'asd' => 2,
    'campaign' => 'true (hit here)',
    'qwe' => 3
);

foreach ($merchant_pic as $key => $value) {
    if(isset($merchant_pic[$key]['campaign'])) {
        echo $merchant_pic[$key]['campaign'];
    }

}

Output: true (hit here)

In this case I don't know what $key is. It's shop, but it could be not_shop, aswell it could be in both, or in another key. It will iterate through all keys and everytime it return true to isset(), it will print it.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.