【问题标题】:How can I get each element of an array如何获取数组的每个元素
【发布时间】:2020-08-11 13:29:57
【问题描述】:

这个数组来自一个数据库。
print_r($row['index']); 输出 Array ( [index] => ["228","227","219","229","60"] ) 我的目标是使用 for 循环分别处理数组的每个元素。所以我想要类似的东西:

for ($x = 0; $x <= sizeof($row['index']); $x++) { 
   $ind = $row['index'][$x]; // first element is 228, then 227, ... 
}

我在应用 json_encode 时得到以下信息

{"to_read_later":"[\"228\",\"227\",\"219\",\"229\",\"60\"]"}

变成这个错误:

警告:json_decode() 期望参数 1 是字符串,给定数组` 我该怎么办?

【问题讨论】:

  • 当 JSON 已经是一个可以循环遍历的数组时,为什么还要应用它? foreach($row['index'] AS $index) {echo $index;} 应该是你所需要的。
  • @JayBlanchard ,它输出$index = ["228","227","219","229","60"]。第一个元素是[。所以它的行为就像一个字符串,而不是一个数组。你知道如何解决这个问题吗?
  • 什么输出?您不必应用 JSON。

标签: php mysql arrays


【解决方案1】:

您的 print_r() 表明 $row 数组具有以下结构:

$row = [
    'index' => [
        'index' => '["228","227","219","229","60"]'
    ]
];

所以json_decode($row['index'], 1) 将返回错误,因为$row['index'] 是一个数组。

相反,您需要应用 json_decode($row['index']['index'], 1) 来解码 json 字符串。

$inds = json_decode($row['index']['index'], 1);

print_r($inds);

应该输出:

Array
(
    [0] => 228
    [1] => 227
    [2] => 219
    [3] => 229
    [4] => 60
)

【讨论】:

  • 您根本不必应用 JSON 方法。 You can just loop through the array 因为它只是一个数组,而不是 JSON。
  • @JayBlanchard 我认为它实际上可能是存储在这个数组中的 JSON,否则 print_r() 会输出Array ( [index] =&gt; Array ( [0] =&gt; 228 [1] =&gt; 227 [2] =&gt; 219 [3] =&gt; 229 [4] =&gt; 60 ) )
  • 不一定,看我的例子。它是一个包含另一个数组的数组。
【解决方案2】:

您的输出中没有 JSON,因此无需应用 json_decode()。您可以像这样简单地遍历您的数组:

$row['index'] = array("index"=>["228","227","219","229","60"]);
foreach($row['index']['index'] as $index) {
    echo $index ."\n";
}

EXAMPLE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 2011-07-08
    • 2016-11-19
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多