我被困住了。我有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 和任务)的表,因此我想打印此信息。
我试图作为起点,但我在第 26 行数组的 C:''xampp''htdocs''test.php 中获得了数组到字符串的转换。这是我尝试过的:
<?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