从字符串更改为 PHP 数组
Change to PHP Array from String
我的数据库中有一个字符串,例如:
$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 like :
$array = explode('{"', $arr);
我对结果和如何得到它感到困惑,
但结果不是我想要的。我希望我只能得到 sku[0] 或 detail[0] 和其他。
您可以使用 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
,这将产生一个关联数组。
我的数据库中有一个字符串,例如:
$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 like :
$array = explode('{"', $arr);
我对结果和如何得到它感到困惑, 但结果不是我想要的。我希望我只能得到 sku[0] 或 detail[0] 和其他。
您可以使用 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
,这将产生一个关联数组。