9951 explained code solutions for 126 technologies


php-redisSave JSON to Redis hash


We assume our JSON is not nested so let's use Redis hashes:

$json = ['a' => 1, 'b' => 2];
array_walk($json, function($v, $k) use ($redis) {
  $redis->hset('json', $k, $v);
});ctrl + c
$json

sample JSON to store to Redis

array_walk

iterate through our JSON

$redis

Redis object after connection

hset

sets hash key and value

json

name of the hash to save our JSON to


Usage example

<?php

$r = new Redis(); 
$r->connect('127.0.0.1', 6379);

$json = ['a' => 1, 'b' => 2];
array_walk($json, function($v, $k) use ($r) {
  $r->hset('json', $k, $v);
});

print_r($r->hgetall('json'));
output
Array
(
    [a] => 1
    [b] => 2
)