john
john

Reputation: 1273

How to grab the keys and value from an array in an array with php

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

}

Upvotes: 2

Views: 157

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

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

Upvotes: 2

Oli
Oli

Reputation: 1190

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
   }

Upvotes: 2

Related Questions