Php 从属性不存在的数组中分配变量';并不总是存在

Php 从属性不存在的数组中分配变量';并不总是存在,php,Php,我使用的API以json格式返回搜索结果。我将其解码到一个PHP数组中,通过在数组上循环并将元素指定为变量,可以从中选择所需的元素,以便将值存储在数据库中 我的问题是可以返回一个或几十个属性,这取决于搜索参数。如果我这样做 $array = json_decode(file_get_contents("http://search-query-url&output=json")); foreach($array as $cur) { $key1 = $cur->item_tit

我使用的API以json格式返回搜索结果。我将其解码到一个PHP数组中,通过在数组上循环并将元素指定为变量,可以从中选择所需的元素,以便将值存储在数据库中

我的问题是可以返回一个或几十个属性,这取决于搜索参数。如果我这样做

$array = json_decode(file_get_contents("http://search-query-url&output=json"));

foreach($array as $cur) {
  $key1 = $cur->item_title;
  $key2 = $cur->item_url;
  $key3 = $cur->item_location;
  echo $key1 . " " . $key2 . " " . $key3 "<br>";
  }
$array=json\u decode(文件获取内容)http://search-query-url&output=json"));
foreach($cur形式的数组){
$key1=$cur->item_title;
$key2=$cur->item\u url;
$key3=$cur->item\u位置;
回显$key1.“$key2.“$key3”
”; }
…除非json输出中不存在项_位置(key3),否则一切正常。在这种情况下,我会得到错误“Undefined property:stdClass::$item\u location”

属性名(item_title、item_url等)很重要,因为这是我知道值/字符串应该存储在哪个表列中的方式

我在试图解决这个问题时被难住了,我不太确定该去哪里。试图在数组或对象中使用,但我一定是做错了什么。我需要根据相应的属性名(如果存在)创建变量


有什么想法吗?谢谢大家!

首先,使用
json\u解码(“json\u字符串”,true)
使其返回数组而不是对象


一旦这样做,
array\u key\u exists()
就会很好地工作。

您可以检查变量是否已设置,如果未设置,则为该键指定一个空白值

foreach($array as $cur) {
  $key1 = (isset($cur->item_title))?($cur->item_title):('');
  $key2 = (isset($cur->item_url))?($cur->item_url):('');
  $key3 = (isset($cur->item_location))?($cur->item_location):('');
  echo $key1 . " " . $key2 . " " . $key3 "<br>";
}
foreach($cur形式的数组){
$key1=(isset($cur->item_title))?($cur->item_title):(“”);
$key2=(isset($cur->item_url))?($cur->item_url):(“”);
$key3=(isset($cur->item_location))?($cur->item_location):(“”);
回显$key1.“$key2.“$key3”
”; }
对于这种情况,我通常的技巧是

  • 使用
    json\u decode($var,true)
    将数据解码为关联数组而不是对象
  • 用于为我所依赖的任何键设置默认值
  • 如果某些字段是可选的,并且您需要知道用户是否提供了输入,请使用
    false
    null
    作为默认值
  • 这消除了语法上不愉快的重复密钥检查

    $array = json_decode(file_get_contents("http://search-query-url&output=json"), true);
    $defaults = array(
        'item_title' => 'Default Title',
        'item_url' => 'default url',
        'item_location' => false
    );
    $array = array_merge($defaults, $array);
    
    // check to see if we have a location or not using !==
    if ($array['item_location'] !== false) {
    
    }
    

    实际上我更喜欢对象语法,但是PHP有很多有用的数组操作函数。此外,许多PHP程序员对数组的使用比对象更为舒适。

    到目前为止,一切都很好-谢谢!您是否建议我对任何/所有不需要的字段使用“false”或“null”?使用一个(a)用户不允许的值,或者(b)是一个合理的默认值。检查“未提供”值时,请确保使用比较操作。由于PHP为您进行了大量类型转换,因此很容易与以下事实发生冲突:
    '==0
    0==false
    false==null
    ==
    运算符不允许类型转换,因此
    false===null
    将失败。