如何解决我如何获得数组的每个元素
此数组来自数据库。 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为字符串,给定数组` 我该怎么办?
解决方法
您的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,因此无需应用json_decode()
。您可以像这样简单地遍历数组:
$row['index'] = array("index"=>["228","60"]);
foreach($row['index']['index'] as $index) {
echo $index ."\n";
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。