Php 仅保留特定子阵列中的前10条记录
我有一些JSON,其格式如下:Php 仅保留特定子阵列中的前10条记录,php,multidimensional-array,filtering,Php,Multidimensional Array,Filtering,我有一些JSON,其格式如下: { "mainKey": [ { "ID": "1018", "dish": "Fish", "desert": "Ice cream", "drink": "Cola" }, { "ID": "1019", "dish": "Pizza", "desert": "Cake", "drink": "Water" }, ...
{
"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);
我需要几个键来取消设置,因此我只需循环数组并取消设置它们:
foreach ($response as $key => $value) {
if($key === 'mainKey') {
}
unset($response['another_key']);
unset($response['yet_another_key']);
}
我不是把所有的钥匙都弄乱,只是几把。我现在要做的是处理main键
,这就是我在循环中包含if语句的原因
如何仅保留mainKey
中的前10条记录?我见过类似于splice
,但这会保留数组中的其他键吗?这是否也会保留我的索引,因为它们对我很重要
考虑到
mainKey
有超过100k条记录,最有效的方法是什么?由于mainKey
将有基于数字的键,您可以创建一个过滤器,删除给定范围之外的所有项
<?php
$json = '{
"mainKey": [
{
"ID": "1018",
"dish": "Fish",
"desert": "Ice cream",
"drink": "Cola"
},
{
"ID": "1019",
"dish": "Pizza",
"desert": "Cake",
"drink": "Water"
}
],
"anotherKey": [
{
"ID": "something",
"dish": "123",
"desert": "123"
}
]
}';
$response = json_decode($json, true);
// If needed, unset your keys
unset($response['anotherKey']);
...
// Now, let's work only with `mainKey`
$mainKey = $response['mainKey'];
// Create a range of keys to keep
$allowed = range(0, 10);
// Finally, filter out all keys not in the range you specified.
$filtered = array_filter(
$mainKey,
function ($key) use ($allowed) {
return in_array($key, $allowed);
},
ARRAY_FILTER_USE_KEY
);
// `$filtered` now only has keys 0-10.
var_dump($filtered);
不需要循环;函数可以以非常简洁的方式完成这项工作
代码:()
或者,这将稍微好一些:
$array = json_decode($json, true);
unset($array['another_key'], $array['yet_another_key']);
$array['mainKey'] = array_slice($array['mainKey'], 0, 10);
创建一个计数器,$i=1代码>在foreach外部,然后是foreach内部的表达式,if($i++>=10)
foreach(数组片($response['mainkey',0,10)as$val){//do staff}unset($response;'mainkey');foreach($val作为响应){//do other}如果您只想使用mainkey
,只需$data=$response['mainkey']代码>我认为这非常接近。它从mainkey中获取前10个元素。但它没有做的一件事是保留我的其他钥匙。如果我想保留另一个键而不是取消设置它,我可以将它与过滤数组一起使用吗?当然-不要unset($response['anotherKey')
然后您可以在需要时检索它:$anotherKeyData=$reponse['anotherKey']
过滤的$filtered
过程过于复杂。在数组()中使用array\u filter()
和range()
和是一个很好的方法。我不推荐这个答案。看我的演示,很公平。很好的解决方案。
$array = json_decode($json, true);
unset($array['another_key'], $array['yet_another_key']);
$array['mainKey'] = array_slice($array['mainKey'], 0, 10);