【发布时间】:2019-12-10 02:54:49
【问题描述】:
我有一些 JSON 格式如下:
{
"mainKey": [
{
"ID": "1018",
"dish": "Fish",
"desert": "Ice cream",
"drink": "Cola"
},
{
"ID": "1019",
"dish": "Pizza",
"desert": "Cake",
"drink": "Water"
},
...
],
"anotherKey": [
{
"something": "something",
"something": 123,
"something": 123
},
...
],
...
}
有很多键和很多数据,我将其缩短以显示基本结构。此 JSON 位于名为 $response 的变量中。我首先将其转换为数组:
$response = json_decode($response, true);
unset 需要几个键,所以我只需循环数组并取消设置它们:
foreach ($response as $key => $value) {
if($key === 'mainKey') {
}
unset($response['another_key']);
unset($response['yet_another_key']);
}
我并没有取消所有键,只是几个键。我现在要做的是在 mainKey 上工作,这就是为什么我在循环中包含一个 if 语句。
如何只保留来自mainKey 的前 10 条记录?我见过像splice 这样的东西,但这会保留我数组中的其他键吗?这是否也会保留我的索引,因为这些索引对我很重要?
考虑到mainKey 拥有超过 10 万条记录,最有效的方法是什么?
【问题讨论】:
-
在 foreach 外创建一个计数器
$i = 1;,然后在 foreach 内创建一个表达式if($i++ >= 10) -
foreach(array_slice($response['mainkey'],0,10) as $val) { // 做人员} unset($response;'mainkey'); foreach($response as $val ) { // 做其他的 }
-
如果你只想和
mainkey合作,你可以简单$data = $response['mainKey'];
标签: php multidimensional-array filtering