php - 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
}
解决方案
您可以通过数组指针或通过第一个键获取键来执行此类操作:
foreach($top5 as $title => $ids) {
echo $title;
echo current($ids); // By array pointer
echo $ids[array_keys($ids)[0]]; // By first key
}
推荐阅读
- node.js - 将数据从服务器(Node.js)发送到 GraphQL 服务器中的客户端(React 组件)
- sql - 从同一行获取非空日期的计数
- python - 使用开始和结束日期左连接
- arrays - 循环遍历数组并根据先前的循环条件设置标志
- python - 电报 API:如何通过电报联系并使用 python @TelethonUpdates 获取状态
- javascript - 单个页面中的多个反应应用程序并使它们保持同步
- python - 有没有更好的方法在 python 中编写嵌套的 if 语句?
- python - 聚类从图像中提取的文本?
- python - Pika 连接丢失错误:pika.exceptions.StreamLostError:流连接丢失:ConnectionResetError(104,'对等连接重置')
- c++ - 为什么我们需要在将项目复制到新文件夹后重新构建已经构建的项目?