runeveryday
runeveryday

Reputation: 2799

how to output the array in php?

Array
(
   [menu-162] => Array
    (
        [attributes] => Array
            (
                [title] => example1
            )

        [href] => node/13
        [title] => test1
    )

[menu-219] => Array
    (
        [attributes] => Array
            (
                [title] => example2
            )

        [href] => node/30
        [title] => test2
    )

)

If I assign the above array to a variable named $hello, now, I want to use a loop only output the menu-162, menu-219.

If I want to only output the attributes title value, if I only want to output the href's value.

How do I write these loops?

Upvotes: 0

Views: 137

Answers (3)

corrodedmonkee
corrodedmonkee

Reputation: 373

foreach($hello as $key => $value) {
    switch($key) {
        case 'menu-162':
        case 'menu-219':
            if($value['href'] && $value['attribute'] && $value['attribute']['title']) {
                $href = $value['href'];
                $attr = $value['attribute']['title'];
            }
        break;
        default:
            continue; //didn't find it
        break;
    }
}

If you do not need the specific menu finding, remove the switch statement. If you do need the specific ids using this is the more scalable solution, and is faster than a nested if. It will also not create notices for variables that don't exist and will only return if both attribute title, and href exist.

Upvotes: 0

Russell Dias
Russell Dias

Reputation: 73292

You can access titles value within the attributes array like so: $hello['menu-162']['attributes']['title'] and for any other 'menu' you can substitute menu-162 with the appropriate menu-number combination. As for the href a simple $hello['menu-162']['href']

As for a loop to access both the values a simple foreach should suffice:

foreach($hello as $value) {
    echo $value['attributes']['title'];
    echo $value['href'];
}

Upvotes: 0

JohnP
JohnP

Reputation: 50019

foreach ($hello as $item) {
  $attr = $item['attributes']['title'];
  $href = $item['href'];
  echo "attr is {$attr}";
  echo "href is {$href}";
}

That should output the attr and href.

Upvotes: 4

Related Questions