2017-06-02 54 views
0

我在SQL數據庫egz設置:{"group":"622","shop":"541","ext":"pdf;mpg;mp4;mpeg;m3u;url"}PHP SQL JSON操作

對於GET PARAM使用此代碼

$setting = $sql->dbquery("SELECT setting FROM public.table"); 
    echo json_decode($setting['setting'],true)['ext']; 

如何插入新的VAL egz:AVI只有當不存在(短代碼)

{"group":"622","shop":"541","ext":"pdf;mpg;mp4;mpeg;m3u;url;avi"} 

或刪除現有VAL egz:PDF

{"group":"622","shop":"541","ext":"mpg;mp4;mpeg;m3u;url"} 

回答

0

你可以寫兩個功能添加如果不存在刪除

$setting = $sql->dbquery("SELECT setting FROM public.table"); 
$ext = json_decode($setting['setting'],true)['ext']; 

$ext = add_if_not_exist($ext, 'avi');// avi exist and not adding 
$ext = add_if_not_exist($ext, 'jpg');//adding jpg 

$ext = remove_item($ext, 'avi'); //remove avi 
$ext = remove_item($ext, 'png'); //png not exist, so not removed 



function add_if_not_exist($ext, $item) { 
    $items = explode(';', $ext); 
    if(!in_array($item, $items)) { 
     $items[]= $item; 
    } 
    $ext = implode(';', $items); 
    return $ext; 
} 


function remove_item($ext, $item) { 
    $items = explode(';', $ext); 
    $key = array_search($item, $items); 
    if($key !== false) { 
     unset($items[$key]); 
    } 
    $ext = implode(';', $items); 
    return $ext; 
}