我最近开始使用php处理json,现在我在联系表单表中的数据库中存储了 json 字符串,从数据库中检索的数据采用以下格式
Array
(
[0] => Array
(
[id] => 18
[data] => {"name":"asdsa","email":"uneebmir321@yahoo.com","phone":"1321","subject":"asdsadsa","message":"ssa"}
)
[1] => Array
(
[id] => 19
[data] => {"name":"uneeb","email":"uneeb@nextcrawl.com","phone":"1232112","subject":"adadas","message":"dasdsa"}
)
[2] => Array
(
[id] => 20
[data] => {"name":"uneeb","email":"uneeb@nextcrawl.com","phone":"1311","subject":"sadasd","message":"sdadas"}
)
[3] => Array
(
[id] => 21
[data] => {"name":"uneeb","email":"uneebmir321@yahoo.com","phone":"13131231","subject":"asda","message":"asdsa"}
)
[4] => Array
(
[id] => 22
[data] => {"name":"asdsad","email":"sads@asda.com","phone":"1231","subject":"asd","message":"saadsa"}
)
)
现在你可以看到id和data属性是两个不同的东西,现在将它们传递给视图我所做的是首先解码json字符串,这是我处理上述场景的方法。
public function retrieve_contact_us(){
$data=$this->Menu->retrieve_contact_us();
$newarray['results']=array();
foreach($data as $d):
array_push($newarray['results'],json_decode($d['data'], true));
endforeach;
echo "<pre>";
print_r($newarray['results']);
//$this->load->view("admin/contactus",$newarray);
}
从上面返回的数组是
Array
(
[0] => Array
(
[name] => asdsa
[email] => uneebmir321@yahoo.com
[phone] => 1321
[subject] => asdsadsa
[message] => ssa
)
[1] => Array
(
[name] => uneeb
[email] => uneeb@nextcrawl.com
[phone] => 1232112
[subject] => adadas
[message] => dasdsa
)
[2] => Array
(
[name] => uneeb
[email] => uneeb@nextcrawl.com
[phone] => 1311
[subject] => sadasd
[message] => sdadas
)
[3] => Array
(
[name] => uneeb
[email] => uneebmir321@yahoo.com
[phone] => 13131231
[subject] => asda
[message] => asdsa
)
[4] => Array
(
[name] => asdsad
[email] => sads@asda.com
[phone] => 1231
[subject] => asd
[message] => saadsa
)
)
现在这就是我想要的,现在我需要添加前端的删除功能,所以逻辑上我需要数据库中每一行的id,你可以在最顶层的数组中看到但是它们是两个不同的东西我是什么实际上想要的是数组就是这样。
Array
(
[0] => Array
(
[id] => 18
[name] => asdsa
[email] => uneebmir321@yahoo.com
[phone] => 1321
[subject] => asdsadsa
[message] => ssa
)
[1] => Array
(
[id] => 19
[name] => uneeb
[email] => uneeb@nextcrawl.com
[phone] => 1232112
[subject] => adadas
[message] => dasdsa
)
)
到目前为止我已经尝试过了!
foreach($data as $d):
array_push($newarray['results'],$d['id']);
array_push($newarray['results'],json_decode($d['data'], true));
endforeach;
现在返回的是,
Array
(
[0] => 18
[1] => Array
(
[name] => asdsa
[email] => uneebmir321@yahoo.com
[phone] => 1321
[subject] => asdsadsa
[message] => ssa
)
[2] => 19
[3] => Array
(
[name] => uneeb
[email] => uneeb@nextcrawl.com
[phone] => 1232112
[subject] => adadas
[message] => dasdsa
)
)
你可以看到它为id创建一个完全独立的索引,我不希望我希望相应的id在数组的相同索引中,因为我们在上面演示了它的值,有什么帮助吗?
答案 0 :(得分:4)
就个人而言,我会用它作为内容的关键。
在循环中你可以这样做:
$newarray['results'][$d['id']] = json_decode($d['data'], true);
如果您需要它作为值,则可以添加它:
$newarray['results'][] = json_decode($d['data'], true) + ['id' => $d['id']];