在php

时间:2018-12-12 09:17:59

标签: php arrays json

我在获取由Android应用程序以post发送的json数组时遇到问题。

PHP代码:

<?php
$properties_json = json_decode($_POST['property'], true);
foreach ($properties_json->properties as $pro_element) {
   echo $pro_element->property_id . '<br/>';
   echo $pro_element->property_name . '<br/>';
   echo $pro_element->property_value . '---------';
}
我发布的

JSON数组:

{
  "properties": [
    {
      "property_id": "654",
      "property_name": "Gender",
      "property_value": "Male"
    },
    {
      "property_id": "655",
      "property_name": "Name",
      "property_value": "Amin"
    },
    {
      "property_id": "656",
      "property_name": "Mobile",
      "property_value": "654-451-456"
    }
  ]
}

错误:

  

为foreach()提供的参数无效

enter image description here

2 个答案:

答案 0 :(得分:2)

json_decode($_POST['property'], true);返回一个数组。在您的代码中,您将其用作对象。这是正确的方法:

<?php
$properties_json = json_decode($_POST['property'], true);

foreach ($properties_json['properties'] as $pro_element) {
   echo $pro_element['property_id'] . '<br/>';
   echo $pro_element['property_name'] . '<br/>';
   echo $pro_element['property_value'] . '---------';
}

编辑:

您可以检查$_POST['property']是否存在并且不为空。

<?php
if(isset($_POST['property'])){
    if($_POST['property'] != null and $_POST['property'] != ""){
        $properties_json = json_decode($_POST['property'], true);

        foreach ($properties_json['properties'] as $pro_element) {
            echo $pro_element['property_id'] . '<br/>';
            echo $pro_element['property_name'] . '<br/>';
            echo $pro_element['property_value'] . '---------';
        }
    }else{
        echo "POST['property'] is empty";
    }
}else{
    echo "Missing POST['property']";
}

答案 1 :(得分:1)

您引用$properties_json->properties就像是一个对象一样,但是您通过执行json_decode($_POST['property'], true);(请参阅documentation of json_decode)将JSON转换为数组

您需要将true更改为false或执行 foreach ($properties_json['properties'] as $pro_element) {