2

print_r($top5) gives me an array like this:

Array ( 
    [title1] => Array ( 
                [id_1] => 4 
                )
    [title2] => Array ( 
                [id_2] => 5 
                ) 
    [title3] => Array ( 
                [id_3] => 8 
                ) 
    [title4] => Array ( 
                [id_4] => 3 
                ) 
    [title5] => Array ( 
                [id_5] => 2 
                ) 
    )

I want to produce an output in a foreach loop where i need all the values of this array:

<a href="page=?"<?php echo $id; ?>"><?php echo $title.' '.$number; ?> 

$top5 is the array and when i use a foreach like below:

foreach($top5 as $key => $val) {
    echo $key // outputs the name of title
    echo $val // outputs nothing;
             // i need to output the id and number as well, belonging to each title

}
2
  • Do not ask several questions in one. Commented May 25, 2020 at 19:56
  • 1
    Why do your arrays have completely different "id" names? Those should at the very least all be id, not id_1, id_2, etc. Commented May 25, 2020 at 20:05

2 Answers 2

2

There are functions to get those if there is only one element or if it will always be the first one:

foreach($top5 as $key => $val) {
    echo $key;
    echo key($val);
    echo current($val);  //can also use reset()
}

You could also use the id key:

foreach($top5 as $key => $val) {
    echo $key;
    echo $id = key($val);
    echo $val[$id];
}
Sign up to request clarification or add additional context in comments.

4 Comments

Nice, key didn't occur to me
Super. Works perfect!
any idea how i can sort the array based on the numbers in descending order? rsort($top5) is not the solution...
That's another question. Make sure to but a var_export of the array in it to make it easier to answer.
2

You could do something like this, either by array pointer or get key by first key:

   foreach($top5 as $title => $ids) {
       echo $title;
       echo current($ids); // By array pointer
       echo $ids[array_keys($ids)[0]]; // By first key
   }

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.