从里面的值获取数组

时间:2018-03-05 18:22:48

标签: php arrays

我目前正在开发一个PHP项目,该项目将使用API​​来获取有关我客户的信息。 API返回JSON中的信息,然后我将其转换为数组。数据由一个大数组组成,其中包含较小的数组。每个较小的阵列都包含每个特定客户的信息。

现在。我如何尽可能高效地使用其中一个较小数组中的值从大数组中获取一个较小的数组?在这个例子中,我有 user_id ,我需要找到它所在的数组。是否有任何函数可以找到数组,还是我需要遍历所有内容,直到找到它为止?

最多可能有1000个较小的阵列,因此我担心循环所有这些值是个好主意。

JSON:

{
"purchases": [
        {
            "user_id": "Remvoed",
            "user_name": "Remvoed",
            "purchase_time": "Remvoed",
            "purchase_revoked": "Remvoed",
            "transaction_id": "Remvoed",
            "price": "Remvoed",
            "is_banned": "Remvoed",
            "ban_endtime": "Remvoed"
        },
        {
            "user_id": "Remvoed",
            "user_name": "Remvoed",
            "purchase_time": "Remvoed",
            "purchase_revoked": "Remvoed",
            "transaction_id": "Remvoed",
            "price": "Remvoed",
            "is_banned": "Remvoed",
            "ban_endtime": "Remvoed"
        },
        {
            "user_id": "Remvoed",
            "user_name": "Remvoed",
            "purchase_time": "Remvoed",
            "purchase_revoked": "Remvoed",
            "transaction_id": "Remvoed",
            "price": "Remvoed",
            "is_banned": "Remvoed",
            "ban_endtime": "Remvoed"
        },
    ]
}

谢谢!

亲切的问候,乔纳森。

2 个答案:

答案 0 :(得分:1)

如果user_id是唯一的,则将JSON解码为数组,提取到由user_id索引的数组并获取该索引。假设您user_id存储了$userid

$result = array_column(json_decode($json, true)['purchases'], null, 'user_id')[$userid];

如果您需要在执行中多次执行此操作,则:

$ids = array_column(json_decode($json, true)['purchases'], null, 'user_id');
$one = $ids[$userid];
$new = $ids[$newid];

答案 1 :(得分:0)

如果您需要查找与您的user_id匹配的多个商品,则无论如何都必须迭代整个purchases数组。如果您愿意,可以使用array_filter

$user_purchases = array_filter($data->purchases, function($purchase) use ($user_id) {
    return $purchase->user_id == $user_id;
});

但是如果user_id在该集合中是唯一的,或者如果您只需要为用户找到一个购买,那么使用循环,因为您可以在找到后立即将其中断一场比赛。如果你使用其中一个array_函数,你将无法获得这种控制级别,而且它将完成整个过程。

$user_purchase = null;
foreach ($data->purchases as $purchase) {
    if ($purchase->user_id == $user_id) {
        $user_purchase = $purchase;
        break;
    }
}
var_dump($user_purchase);
相关问题