Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何获取数组的每个元素_Php_Mysql_Arrays - Fatal编程技术网

Php 如何获取数组的每个元素

Php 如何获取数组的每个元素,php,mysql,arrays,Php,Mysql,Arrays,此数组来自数据库 print_r($row['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, ... } 然后变成这个错误: 警告:js

此数组来自数据库
print_r($row['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_decode()要求参数1为字符串,数组给定` 我怎么办

print_r()表示$row数组具有以下结构:

$row = [
    'index' => [
        'index' => '["228","227","219","229","60"]'
    ]
];
因此
json\u 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\u decode()
。您可以像这样简单地在阵列中循环:

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

既然JSON已经是一个可以循环使用的数组,为什么还要应用它
foreach($row['index']AS$index){echo$index;}
应该是您所需要的一切。@JayBlanchard,它输出
$index=[“228”、“227”、“219”、“229”、“60”]
。第一个元素是
[
。所以它的行为就像一个字符串,而不是一个数组。你知道如何解决这个问题吗?这是什么输出?你不必应用JSON。你根本不必应用JSON方法。因为它只是一个数组,而不是JSON。@JayBlanchard我想它实际上可能是存储在这个数组中的JSON,否则print\r()将有输出
Array([index]=>Array([0]=>228[1]=>227[2]=>219[3]=>229[4]=>60))
不一定,请参见我的示例。它是一个包含另一个数组的数组。
$row['index'] = array("index"=>["228","227","219","229","60"]);
foreach($row['index']['index'] as $index) {
    echo $index ."\n";
}