从字符串

时间:2018-08-05 14:19:17

标签: php arrays explode

我有一个来自数据库的字符串,例如:

$arr = [{"detail":"33,putih","sku":"123","price":"21","stok":"5"},{"detail":"33,hitam","sku":"528","price":"75","stok":"5"},{"detail":"34,hitam","sku":"775","price":"49","stok":"5"}]

但是我想将此字符串转换为数组,我曾尝试使用explode像:

$array = explode('{"', $arr);
我对结果和获得方法感到困惑, 但是结果不像我想要的。我希望我只能得到sku [0]或detail [0]等等。

1 个答案:

答案 0 :(得分:1)

您可以在PHP中使用json_decode()方法将JSON字符串转换为array

$str_json = '[{"detail":"33,putih","sku":"123","price":"21","stok":"5"},{"detail":"33,hitam","sku":"528","price":"75","stok":"5"},{"detail":"34,hitam","sku":"775","price":"49","stok":"5"}]';

$arr = json_decode($str_json,true);

json_decode()函数的第二个参数设置为true,这将导致一个关联数组。