【问题标题】:Php array in array Warning: Illegal string offset数组中的 PHP 数组警告:非法字符串偏移
【发布时间】:2017-10-07 07:04:18
【问题描述】:

我有这个数组

//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"
}

错误:

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

          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']);它以字符串形式显示所有内容

【问题讨论】:

标签: php arrays


【解决方案1】:

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

我在我的项目中使用了很多数组,这些提示应该有助于追踪问题。

【讨论】:

    【解决方案2】:

    那是因为,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;
    ?>

    【讨论】:

    • 现在在不同的网站上工作会在一些时候尝试一下
    • 原来它正在查看每个数组,就像它是自己的数组一样
    猜你喜欢
    • 1970-01-01
    • 2013-04-11
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多