数组中的Php数组警告:非法字符串偏移量

时间:2017-10-06 21:59:36

标签: php arrays

我有这个数组

//this is onw part of `$pins['location']`
array(9) {
  ["address"]=> string(23) "11xxx Hudderfield xxxxxx"
  ["city"]=> string(12) "Jxxxxxx"
  ["houseNumber"]=> string(5) "11xxx"
  ["id"]=> NULL
  ["state"]=> string(2) "xx"
  ["country"]=> NULL
  ["street"]=> string(17) "Hudderfield xxxxx"
  ["unit"]=> NULL
  ["zip"]=> string(5) "xxxx"
}

错误:

当代码运行时,它位于一个更大的数组中我得到错误警告:非法字符串偏移'地址'在/home/../../../cron.php第77行

          76  foreach ($pins['location'] as $pin_lo) {
          77      $location_address = $pin_lo['address'];
          78      echo $location_address;
          79      $location_city = $pin_lo['city'];
          80      echo $location_city;
          81  }

我需要能够将数组值传递给变量,如您所见。如果我dd($ pins [' location']);它显示所有字符串不确定当数组在foreach之后发生变化时它只会返回每行的第一个字母或数字吗?

2 个答案:

答案 0 :(得分:0)

问题出在你的$ pins数组的构造中。在运行foreach循环时,尝试在检索地址值之前转储$ pin_lo。我认为$ pin_lo是一个字符串而不是数组。

我在项目中使用了大量数组,这些提示应该有助于跟踪问题。

答案 1 :(得分:0)

这是因为PHP没有像Java HASH_MAP这样的映射支持功能。因此,不幸的是,您需要自己构建它。这是你在寻找什么?



<?php

$pins = [
    "address" => "11xxx Hudderfield xxxxxx",
    "city" => "Jxxxxxx",
    "id" => null,
    "state" => "xx",
    "country" => NULL,
    "street" => "Hudderfield xxxxx",
    "unit" => NULL,
    "zip" => "xxxx"
];

foreach ($pins as $key => $value):
    switch ($key):
        case "address":
            $location_address = $value;
            break;
        case "city":
            $location_city = $value;
            break;
    endswitch;
endforeach;

echo "Address: ".$location_address;
echo "</br>";
echo "City: ".$location_city;
?>
&#13;
&#13;
&#13;