Foreach 用于复杂数组

Foreach for complex array

我受困于此。我有 0 个想法可以做到这一点。我在 json:

中有这个字符串
$json = json_encode(
array(
    'error'=> 'false',
        'tasks' => array(
            1 => array(
                'id' => 4,
                'task' => 'Prueba'
            ),
            2 => array(
                'id' => 9,
                'task' => 'Psdasdrueba'
            ),
        ),
    )
);

我猜 json 代码是正确的。如果没有,我想我想做的结构已经很清楚了。

所以现在我想用 foreach 提取任务。因此,每次循环运行时,它都会从数组任务中获取一个值(示例 1)。之后,我创建了一个包含两个列(id 和任务)的 table,所以我想打印此信息。

我试图以此作为起点,但我在 C:\xampp\htdocs\test.php 的第 26 行数组中获得了数组到字符串的转换。 这是我试过的:

<?php
// Encode the data.
$json = json_encode(
array(
    'error'=> 'false',
        'tasks' => array(
            1 => array(
                'id' => 4,
                'task' => 'Prueba'
            ),
            2 => array(
                'id' => 9,
                'task' => 'Psdasdrueba'
            ),
        ),
    )
);

// Define the errors.
$constants = get_defined_constants(true);
$json_errors = array();

$response = json_decode($json, true);
// Show the errors for different depths.
foreach (range(4, 3, -1) as $depth) {
echo $response;
}
?>

你总是想打印 $response 数组。遍历任务数组:

foreach ($response['tasks'] as $item) {
    echo "Id: " . $item['id']."<br />";
    echo "task: " . $item['task'] . "<hr />";
}

试试这个...

<?php
$json = json_encode(
array(
    'error'=> 'false',
        'tasks' => array(
            1 => array(
                'id' => 4,
                'task' => 'Prueba'
            ),
            2 => array(
                'id' => 9,
                'task' => 'Psdasdrueba'
            ),
        ),
    )
);
$response = json_decode($json, true);

foreach($response['tasks'] as $value)
{
echo "Id:".$value['id']."</br>";
echo "Task:".$value['task']."</br>";
}
?>

输出:

Id:4
Task:Prueba
Id:9
Task:Psdasdrueba