0

I have the following array:

$features = array(
    array(
        'name'    => 'Communication',
        'plans'    => array(
            'standard'  => 'yes',
            'advanced'  => 'yes'
        )
    ),
    array(
        'name'    => 'French',
        'plans'    => array(
            'standard'  => 'no',
            'advanced'  => 'yes'
        )
    )
);

How can I output this:

- Communication : standard > yes
- Communication : advanced > yes
- French : standard > no
- French : advanced > yes

What I tried:

foreach ($features as $feature => $info) {
    echo $feature['name'].' : ' ['plans']['standard'].' > '.$feature['name']['plans']['standard'].'<br />';
    echo $feature['name'].' : ' ['plans']['standard'].' > '.$feature['name']['plans']['advanced'].'<br />';
}

But it doesn't work because nothing is outputted.

Could you please help me ?

Thanks.

  • Your error reporting is turned off so you're not seeing all of the `Warning: Illegal string offset` messages. If you wish to turn it on then see https://stackoverflow.com/q/1053424/2191572 – MonkeyZeus Aug 27 '18 at 18:18

3 Answers3

1

Try this:

foreach ($features as $feature => $info) {
    echo $info['name'].' : standard > ' . $info['plans']['standard'].'<br />';
    echo $info['name'].' : advanced > ' . $info['plans']['advanced'].'<br />';
}

You are referring to the wrong variable in your loop

Onfire
  • 336
  • 3
  • 13
1

This should do the trick. You should used $info to access the data inside because everytime you do a foreach loop, you get inside the parent array.

$features = array(
    array(
        'name'    => 'Communication',
        'plans'    => array(
            'standard'  => 'yes',
            'advanced'  => 'yes'
        )
    ),
    array(
        'name'    => 'French',
        'plans'    => array(
            'standard'  => 'no',
            'advanced'  => 'yes'
        )
    )
);

foreach ($features as $feature => $info) {
    echo $info['name']. ' : standard > '. $info['plans']['standard'] . '<br />'; 
    echo $info['name']. ' : advanced > '. $info['plans']['advanced'] . '<br />'; 
}
bastien
  • 414
  • 7
  • 14
1

You should use a nested for loop as plans itself is an array as follows

foreach ($features as $feature) {

    foreach($feature['plans'] as $key=>$val){
        echo $feature['name'].' : '. $key.' > '.$val.'<br />';

    }
}

I got the following output

Communication : standard > yes
Communication : advanced > yes
French : standard > no
French : advanced > yes
Rinsad Ahmed
  • 1,877
  • 1
  • 10
  • 28