【问题标题】:how to convert this string to an array?如何将此字符串转换为数组?
【发布时间】:2020-02-18 12:03:43
【问题描述】:

我正在尝试将我在 JS 中创建的这个数组转换为然后在我的控制器中使用以在 foreach 中使用并使用数组的数据。我正在使用框架 codeigniter。

在这里我在我的 JS 文件中创建数组。

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) {

        }
    });
}

我发送给控制器的数据如下所示。 [{"item":"1","cantidad":"2"},{"item":"2","cantidad":"4"}]

现在是我的控制器 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>';
   }
}

var_dump($items) 这就是结果

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

在这个回声中我得到了这个错误Message: Trying to get property 'item' of non-object

我不知道我做错了什么

【问题讨论】:

  • datos 不是还在字符串化吗?

标签: javascript php codeigniter


【解决方案1】:

看起来像标准的 JSON。 请务必在 json_decode 函数(第二个参数)中添加 true 以返回数组而不是对象。

$result = json_decode($data, true); 

看看 JSON,因为它是当今 Web 和移动应用程序数据交换的标准,并了解有关该功能的更多信息:

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

还可以查看将您的数组编码为 JSON 格式的对应项:

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

【讨论】:

  • 并在 echo $row->item;仍然得到这个Message: Trying to get property 'item' of non-object
  • 这不是一个对象,这意味着您需要将其作为数组访问,即 foreach ($result as $row) { echo $row['item']; } 。如果要获取对象数组,请从解码函数中删除 true。
【解决方案2】:

您可以将此代码用作分解返回数组,而不是对象。

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>';
   }

【讨论】:

    【解决方案3】:

    有两种情况:

    1. 如果你想解析JSON对象,那么

      $items = json_decode($data); // instead of $items = explode(',', $data);
      
    2. 如果您想将数据视为字符串,则

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

    【讨论】:

    • Message: Cannot use object of type stdClass as array
    猜你喜欢
    • 2021-11-26
    • 2012-05-18
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    相关资源
    最近更新 更多