Wednesday, 29 August 2018

echo a multidimensional array in php with variables

I am trying to get the data from a multidimensional array key in php. The array structure is like this :

Array

( [status] => 1     [embeds] => Array
    (
        [1] => Array
            (
                [embed] => <IFRAME SRC="XXXXXXXX.ZZZ" FRAMEBORDER="0" MARGINWIDTH="0" MARGINHEIGHT="0" SCROLLING="NO" WIDTH="620" HEIGHT="360"></IFRAME>
                [link] => http://XXXXXXXXXXX.ZZZZ
                [language] => ENG
            )

        [2] => Array
            (
                [embed] => <iframe src="http://www.XXXXXXX.ZZZZ" width="620" height="360" frameborder="0" scrolling="no"></iframe>
                [link] => http://www.XXXXXXX.ZZZZZ
                [language] => ENG
            ) ... ... ... ...

    ))

The $auto_incrementing_value starts from 1 to as many as there are. so if I want to echo only 1 data and $auto_incrementing_value = 1, I can do echo $ret['embeds'][$auto_incrementing_value]['link']; What I want to do is echo all the "link" value from all the arrays.
I tried this code but it does not work :
$codes = 1;
foreach ($ret as $key => $rets){
echo $ret['embeds'][$codes]['link'];
$codes++;
}


That sure is some whacky syntax you've got going on there. You're using a foreachloop like a while loop that is written like a for loop.
Try:
foreach ($ret['embeds'] as $embed){
  echo $embed['link'];
}

Or:
for( $i=1; $i<=count($ret['embeds']); $i++ ) {
  echo $ret['embeds'][$i]['link'];
}

Or if you want to get saucy:
$i=0;
while($i<=count($ret['embeds'])) {
  echo $ret['embeds'][$i]['link'];
  $i++;
}

edit

Raises a valid point about calling count() [or really any function] in the loop condition. If the function's return will be static during the entire course of the loop [ie: the number of elements in the array doesn't change] then it's best to do:
$count = count($ret['embeds'];
for( $i=1; $i<=$count; $i++ ) {
  echo $ret['embeds'][$i]['link'];
}

Or, alternatively, you can go backwards:
for( $i=count($ret['embeds'])-1; $i>=0; $i-- ) {
  echo $ret['embeds'][$i]['link'];
}

0 comments:

Post a Comment