php - 循环遍历 Laravel 集合并使用 Redis 存储到 key

标签 php arrays json laravel redis

作为 redis 的完全业余爱好者,我可能会以完全错误的方式处理事情,有人怀疑我是在给自己找麻烦。话虽这么说,我正在学习基础知识并努力实现我认为可行的结果。

我在 MySQL 中有一个相当大的数据库,其中包含 4000 万条记录。

由于我还不知道 Redis 的全部要点以及导入方法和正确的数据结构,所以我想到了一个基本方法:

使用 laravel eloquent 查询 MySQL,遍历结果并调用 redis set 将值存储到键中。

事情是这样的,数据库是OK的邮政编码和地址,每个邮政编码包含很多个地址。

到目前为止,这是我的代码:

    $addresses = UkAddresses::where('postcode', 'N10AB')->get();
    $contCount = count($addresses);

    for ($x = 0; $x < $contCount; $x++) {
        $postcode = $addresses[$x]['postcode'];
        $redis = Redis::connection();
        $redis->set('postcodes.' . $postcode, json_encode(array(
                    'postcode' => $postcode,
                    'addresses' => array(
                        $addresses[$x]['address']
                    )
                )
            )
        );
        $response = $redis->get('postcodes.'.$postcode);
        $response = json_decode($response);
    }

一切正常,除了它只为该邮政编码插入一个地址,如果我使用 get postcode.N10AB

,这是一个示例插入
{"postcode":"N10AB","addresses":["N10AB, Arena Enterprises UK Ltd, Flat 37, Selkirk House, Bemerton Estate, London "]}

我的猜测是在遍历从 Laravel 返回的数组时我的循环有问题,这就是为什么只有 1 个结果被传递给 Redis 的原因?

这是从 MySQL 返回的数组,我试图循环并插入到 Redis 中。

[0] 
postcode    "N10AB"
address "N1 0AB, Arena Enterprises UK Ltd, Flat 37, Selkirk House, Bemerton Estate, London "

[1]
postcode    "N10AB"
address "N1 0AB, Dumas Services, Flat 10, Selkirk House, Bemerton Estate, London "

最佳答案

我不会说这是完美和理想的解决方案,但我在下面找到了一个可行的解决方案,以防将来有人遇到与我类似的情况。

    $addresses = UkAddresses::where('postcode', 'N10AB')->get();
    $postcode = $addresses->first()->postcode;
    $items = array();
    foreach($addresses as $address){
        $items[] = $address['address'];
    }
    $redis = Redis::connection();
    $redis->set('postcodes.' . $postcode, json_encode(array(
                'postcode' => $postcode,
                'addresses' => $items
            )
        )
    );
    $response = $redis->get('postcodes.' . $postcode);
    $response = json_decode($response);
    return response()->json($response);

我很想听听其他人的看法,因为我确信有一种更简单、更清晰的方法。

关于php - 循环遍历 Laravel 集合并使用 Redis 存储到 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41052929/

相关文章:

android - 无法更新从 json 创建的 getstream Activity

php - 如何让用户为不同的事件连续创建相同的 HTML 表单?

PHP Paypal IPN 获取交易数组

javascript - 使用 jquery ajax 将数据 POST 到 JSON 数组中?

ios - 我如何准备 segue 在我的 TableViewController 中加载不同的数组?

arrays - Array.reduce 无法通过下标赋值 : 'x' is a 'let' constant

javascript - 如何将我的 JSON 文件解析为我可以在 React js 中操作的对象

php - Symfony 2 表单级联验证

php - Laravel Blade View - undefined variable : errors

ios - 在 Swift 中将字符串拆分为数组?