0
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?

2
  • 4
    This is really basic stuff. Have you tried anything? Looked at the foreach documentation? Tried to loop through the array and print_r on each iteration to see what you can work with? Commented Feb 23, 2011 at 5:14
  • please add an example of what you would expect the output to be look like Commented Feb 23, 2011 at 5:15

3 Answers 3

4
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0
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.

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.