Home » Php » javascript – how to convert this string to an array?

javascript – how to convert this string to an array?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to convert this array I create in JS to then used in my controller to used in a foreach and used the data of the array. I’m using the framework codeigniter.

Here where I create the array in my JS file.

function get_array(){
  var datos = []; // Array
  $("#tbl_esctructura tbody > tr").each(function() {

    var item = $(this).find('td:eq(1)').text();
    var cantidad = $(this).find('td:eq(4)').text();

    datos.push({
       "item": item,
       "cantidad": cantidad
    });
  });

  datos =  JSON.stringify(datos); 
  $.ajax({
        data: {
            'datos': datos
        },
        url: "<?php echo base_url() ?>Controller/data_from_array",
        type: 'POST',
        dataType : "json",
        success: function(response) {

        }
    });
}

the data I send to the controller look like this.
[{"item":"1","cantidad":"2"},{"item":"2","cantidad":"4"}]

Now my controller PHP

public function data_from_array(){
   $data   =  $this->input->post('datos', TRUE);
   $items = explode(',', $data);
   var_dump($items);
   foreach ($items as $row) {
       echo  $row->item.'<br>';
   }
}

and the var_dump($items) this is the result

array(2) { [0]=> string(12) "[{"item":"1"" [1]=> string(16) ""cantidad":"1"}]" }
}

And in this echo I get this error Message: Trying to get property 'item' of non-object

And I don’t know what I’m doing wrong

How to&Answers:

Looks like a standard JSON.
Be sure to add true to json_decode function (second parameter) to return array instead of object.

$result = json_decode($data, true); 

Have a look at JSON as this is a, nowadays, standard of data interchange for web and mobile apps and learn more about the function:

https://www.php.net/manual/en/function.json-decode.php

also look at its counterpart that will encode your arrays into JSON format:

https://www.php.net/manual/en/function.json-encode.php

Answer:

You can use this code as the explode return array, not an object.

public function data_from_array(){
  $data   =  $this->input->post('datos', TRUE);
  $items = explode(',', $data);
  var_dump($items);
   foreach ($items as $row) {
      echo  $row["item"].'<br>';
   }

Answer:

there are two scenarios:

  1. if you want to parse JSON object, then

    $items = json_decode($data); // instead of $items = explode(',', $data);
    
  2. if you want to treat data as a strings then

    echo  $row[0].'<br>'; // instead of echo  $row->item.'<br>';