Search code examples
phparraysjsoncodeigniter-4

I want to read all data from Json array in Php codeigniter 4


I have generated html table data to Json array using jquery, it worked for me and I got the array below, I need php code to iterate each value of this array in php codeigniter 4 controller.

array(1){
  [
    0
  ]=>string(966)"[{"ID":"\n2","Name":"\nCP","Price":"\n350.20"},{"ID":"\n3","Name":"\nLFT","Price":"\n700.10"},{"ID":"\n4","Name":"\nRFT","Price":"\n200"},{"ID":"\n5","Name":"\nurinetest","Price":"\n1000"}]"
}


Solution

  • It's a php array that contains a json array, if you are sure you will only have one element in the array, you can do so:

    $array = json_decode($var[0]); // $var holds the data you mentioned above
    foreach ($array as $item) {
        //
    }
    

    otherwise:

    foreach ($var as $array) { // $var holds the data you mentioned above
        $array = json_decode($array);
        foreach ($array as $item) {
            //
        }
    }