動態字段插入及查詢redis小結

對於對象,如[],{} 入redis必需先轉化成string,不然沒法正確的存入redis

插入\更新

$objFields = array("fuck")

$params = array("name"=>"hello","age"=>1,"tags"=>array("sexy","handsome"));

$params = obj2string($params,$objFields);


$redis->hMset('sbase:detail:1',$params);

查詢列表

$objFields = array("fuck")

$result = $redis->hGetAll('sbase:detail:1');

$result = string2obj($result,$objFields);

return $result;

準備幫助函數

/**
     * @param $Params
     * @param $objFields
     * @return mixed
     */
    public function obj2string($Params,$objFields) {
        if(count($objFields)>0) {
            foreach ($objFields as $field) {
                $Params[$field] = json_encode($Params[$field]);
            }
        }

        return $Params;
    }

    /**
     * @param $result
     * @param $objFields
     * @return mixed
     */
    public function string2obj($result,$objFields) {
        //to process
        if(count($objFields)>0) {
            foreach ($objFields as $field) {
                $result[$field] = json_decode($result[$field]);
            }
        }

        return $result;
    }


    /**
     * @param $items
     * @param $objFields
     * @return array
     */
    public function list2obj($items,$objFields) {
        //to process
        if(count($objFields)>0) {
            $temps = array();
            foreach($objFields as $field) {
                foreach($items as $item){
                    $item[$field] = json_decode($item[$field]);
                    array_push($temps,$item);
                }
            }
            $items = $temps;
        }

        return $items;
    }
相關文章
相關標籤/搜索