首页 > 解决方案 > 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

}

标签: phparrays

解决方案


您可以通过数组指针或通过第一个键获取键来执行此类操作:

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

推荐阅读