1. 程式人生 > >php解析字串成json再轉成陣列

php解析字串成json再轉成陣列

//字串裝json再轉陣列
$data=$this->str_change($_POST['upimg']);

/**
 * 物件 轉 陣列
 *
 * @param object $obj 物件
 * @return array
 */
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }

        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }

    return $obj;
}

/**
 * 將字串轉換為物件再轉換為陣列
 *
 * @param    string    $data    字串
 * @return    array    返回陣列格式,如果,data為空,則返回空陣列
 */
function str_change($data) {
    $str=str_replace('[','',$data);
    $str=str_replace(']','',$str);
    $str=stripslashes($str);
    $upimg=explode('},',$str);
    $upimg=str_replace('}','',$upimg);
    $arr=[];
    foreach ($upimg as $k=>$v){
        $new=$v.'}';
        array_push($arr,$this->object_to_array(json_decode($new)));
    }
    return $arr;
}