gpt4 book ai didi

PHP JSON 获取键和值

转载 作者:行者123 更新时间:2023-12-03 22:53:42 26 4
gpt4 key购买 nike

我有以下 JSON 格式:

{
"S01": ["001.cbf", "002.cbf", "003.cbf", "004.cbf", "005.cbf", "006.cbf", "007.cbf", "008.cbf", "009.cbf"],
"S02": ["001.sda", "002.sda", "003.sda"],
"S03": ["001.klm", "002.klm"]
}

我尝试使用此代码:
$json = json_decode('{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}');

foreach($json as $key => $val) {
if ($key) { echo 'KEY IS: '.$key; };
if ($val) { echo 'VALUE IS: '.$value; };
echo '<br>';
}

但我得到了空的结果......我需要得到这样的输出:
KEY IS: S01
VALUE IS: 001.cbf
VALUE IS: 002.cbf
VALUE IS: 003.cbf
VALUE IS: 004.cbf
VALUE IS: 005.cbf
VALUE IS: 006.cbf
VALUE IS: 007.cbf
VALUE IS: 008.cbf
VALUE IS: 009.cbf

KEY IS: S02
VALUE IS: 001.sda
VALUE IS: 002.sda
VALUE IS: 003.sda

KEY IS: S03
VALUE IS: 001.klm
VALUE IS: 002.klm

这是我需要的,以便我可以使用值和键名生成 ul 和 li 元素……这是存储在 mysql 数据库中的 JSON 格式,并被读取到需要解析上述输出中的 JSON 的 php 脚本,以便我可以使用输出创建 ul 和 li 元素。

我尝试执行 foreach 但结果为空?我知道当我获得值(value)时,我需要使用 explode(', ', $value) 来做爆炸字符串但我无法在 PHP 中根据需要读取 $value 和 $key。

最佳答案

这解决了您的问题,您必须将 $json 转换为数组,因为它被视为 stdClass 对象;)

<?php 
$json = json_decode('{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}');
foreach($json as $key => $val) {
echo "KEY IS: $key<br/>";
foreach(((array)$json)[$key] as $val2) {
echo "VALUE IS: $val2<br/>";
}
}
?>

Try It Online!

我建议您下次遇到麻烦时使用函数 var_dump($var),它会帮助您找出问题所在。

关于PHP JSON 获取键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48095298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com