










當下做開發(fā)的用對象存儲數(shù)據(jù)非常多了,如微信小程序開發(fā)中的云開發(fā)存儲數(shù)據(jù)就是以對象方式保存的,還有相當多的API接口也是以JSON方式傳輸數(shù)據(jù)。
這次補充開發(fā)商品功能的規(guī)格模板時就使用對象方式存在數(shù)據(jù)庫了,當然用兩個表一對多方式關聯(lián)也是非常方便,那么這次的開發(fā)會用到對象與數(shù)組互轉的功能,現(xiàn)把整個功能記錄下來。
首先數(shù)據(jù)表保存的字段內(nèi)容:
$attr_list='[{"attr_id":"1","attr_name":"3R"},{"attr_id":"1","attr_name":"4R"},{"attr_id":"1","attr_name":"5R"},{"attr_id":"1","attr_name":"6R"},{"attr_id":"1","attr_name":"10寸"},{"attr_id":"1","attr_name":"12寸"},{"attr_id":"1","attr_name":"16寸"},{"attr_id":"1","attr_name":"18寸"]';
在數(shù)據(jù)表中取出這樣字段,我們需要把attr_name按列表方式顯示,如下圖:
按鈕底紋的樣式,大家可以直接復制使用,CSS和HTML代碼如下:
<div class="attr-name">淋膜</div>
.attr-name {
background: #f3f3f3;
color: #666666;
display: inline-block;
line-height: 32px;
margin: 5px;
border-radius: 5px;
padding: 0 15px;
}
php先通過json_decode進行轉換再使用object_array函數(shù)將對象轉成數(shù)組,代碼如下:
$str_list='[{"attr_id":"1","attr_name":"淋膜"},{"attr_id":"1","attr_name":"冷裱"},{"attr_id":"1","attr_name":"塑封"}]';
$str_arr=object_array(json_decode($str_list));
for($i=0;$i<count($str_arr);$i++)
echo '<div class="attr-name">'.$str_arr[$i]['attr_name'].'</div>';
/*object_array是對象轉成數(shù)組函數(shù)*/
function object_array($array) {
if(is_object($array)) {
$array = (array)$array;
} if(is_array($array)) {
foreach($array as $key=>$value) {
$array[$key] = object_array($value);
}
}
return $array;
}
接下來我們還需要把數(shù)據(jù)存回數(shù)據(jù)表,如用戶錄入或修改,這個就比較容易了,代碼如下:
$str_arr[0]['attr_id']=1;
$str_arr[0]['attr_name']="淋膜";
$str_arr[1]['attr_id']=2;
$str_arr[1]['attr_name']="冷裱";
$str_object=json_encode($str_arr,JSON_UNESCAPED_UNICODE);
使用json_encode時要注意事項,如果是5.3以后的版本按以上代碼即可,加了JSON_UNESCAPED_UNICODE這個參數(shù)后,保存在數(shù)據(jù)表的字符將不會采用編碼后方式保存,不加參數(shù),對于存數(shù)據(jù)表的數(shù)據(jù)就沒有這么直觀。
規(guī)格模板完事,接下來還要應用到商品管理中,這個又稍復雜點,到時再寫一篇文章介紹。