php怎么把数据库数据转成json格式,例如"phone""123456"改为"name""phone""value""123456"

WBOY
發布: 2016-06-13 12:14:32
原創
1084 人瀏覽過

php如何把数据库数据转成json格式,例如"phone":"123456"改为"name":"phone","value":"123456"
怎么把"phone":"1234567"  改成 "name":"phone","value":"123456"。。
------解决思路----------------------

$s = '{"phone":"1234567"}';<br /><br />$a = json_decode($s, 1);<br />foreach($a as $k=>$v) $r[] = array('name' => $k, 'value' => $v);<br /><br />echo json_encode($r);<br />
登入後複製
[{"name":"phone","value":"1234567"}]

------解决思路----------------------
<br />$a = '{"phone":"1234567"}';<br />$ret = array();<br />$arr = json_decode($a, true); <br />foreach($arr as $key=>$val){<br />    array_push($ret, array('name'=>$key,'value'=>$val));<br />}<br /><br />echo json_encode($ret);<br />
登入後複製


[{"name":"phone","value":"1234567"}]
------解决思路----------------------
<br />$s="'phone':'1234567'";<br />$arr=explode(':',$s);<br />for($i=0;$i<sizeof($arr);$i++){<br />    $item=array('name'=>current($arr),'value'=>next($arr));<br />    break;<br />}<br />echo json_encode($item);<br />
登入後複製

<br />{"name":"'phone'","value":"'1234567'"}<br />
登入後複製

------解决思路----------------------
$s = '[{"phone":"18511337033","name":"ggg","id_card":"123321123321"}]';<br />$a = json_decode($s, 1);<br /><br />foreach($a as $t) {<br />  $r = array();<br />  foreach($t as $k=>$v) $r[] = array('name' => $k, 'value' => $v);<br />  $res[] = $r;<br />}<br /><br />echo json_encode($res);<br />
登入後複製
登入後複製
[[{"name":"phone","value":"18511337033"},{"name":"name","value":"ggg"},{"name":"id_card","value":"123321123321"}]]

------解决思路----------------------
引用:
Quote: 引用:

$s = '[{"phone":"18511337033","name":"ggg","id_card":"123321123321"}]';<br />$a = json_decode($s, 1);<br /><br />foreach($a as $t) {<br />  $r = array();<br />  foreach($t as $k=>$v) $r[] = array('name' => $k, 'value' => $v);<br />  $res[] = $r;<br />}<br /><br />echo json_encode($res);<br />
登入後複製
登入後複製
[[{"name":"phone","value":"18511337033"},{"name":"name","value":"ggg"},{"name":"id_card","value":"123321123321"}]]


。。现在还有个需求。。 就是怎么做才可以输出出来的不是两个[[{"name":"111","value":"222" }]],
只输出一个方括号[{"name":"111","value":"222" }]


改這樣:

<br />$s = '[{"phone":"18511337033","name":"ggg","id_card":"123321123321"}]';<br />$a = json_decode($s, 1);<br /> <br />foreach($a as $t) {<br />  $r = array();<br />  foreach($t as $k=>$v) $r[] = array('name' => $k, 'value' => $v);<br />  $res[] = $r;<br />}<br /> <br />echo json_encode(array_pop($res));<br />
登入後複製


[{"name":"phone","value":"18511337033"},{"name":"name","value":"ggg"},{"name":"id_card","value":"123321123321"}]

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!