Search code examples
phparraysexplode

Change to PHP Array from String


I Have an string from my database, like :

$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"}]

But i want to convert this string to array, i was try use explode like :

$array = explode('{"', $arr);

i was confused of the result and how to get it, But the result not like i want. I want i can get only sku[0] or detail[0] and else.


Solution

  • You can use json_decode() method in PHP to convert your JSON string to 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);
    

    The second parameter of json_decode() function is set to true which will result in an associative array.