php - 从表中获取关联数组中元素的值
问题描述
$arr = ['b1' => 'banners/5B5C4965B9A50.jpg', 'vid' => 'vid.mp4', 'linked' => 'linkedabc'];
我将上面的数组插入到一个表中(使用json_encode
),所以命名的文件的内容map
是:
{"b1":"banners/5B5C4965B9A50.jpg","vid":"vid.mp4","linked":"linkedabc"}
现在我想获取并循环这个数组:
$sql = "select map from params where what = 'artb'";
$st = $db->prepare($sql);
$st->execute();
$arrx = $st->fetch();
//$arrx = json_decode($arrx); - also tried here
foreach($arrx as $key => $el){
if($key == 'b1') {getb1($el);}
}
function getb1($el){
echo $el;
}
结果:
{"b1":"banners/5B5C4965B9A50.jpg","vid":"vid.mp4","linked":"linkedabc"}
我期待着banners/5B5C4965B9A50.jpg
。
怎么了?
解决方案
$arrx = json_decode($arrx,true);
foreach($arrx as $key => $el){
if($key == 'b1') {getb1($el);}
}
在循环之前需要一个数组。您尝试以访问数组的方式访问 json 对象,这是不可能的。
之后,您的代码将完美运行。
$data = '{"b1":"banners/5B5C4965B9A50.jpg","vid":"vid.mp4","linked":"linkedabc"}';
$arrx = json_decode($data,true);
foreach($arrx as $key => $el){
if($key == 'b1') {getb1($el);}
}
function getb1($el){
echo $el;
}
并且输出banners/5B5C4965B9A50.jpg
符合预期
推荐阅读
- go - 使用 aws-sdk-go 在 Dynamo DB 中构建“IN”查询
- angular - 将数据传递给 index.html
- python - 如何在 Python 中复制列表列表?
- java - 如何在 Java 中连接到数据库 - EDT 时区
- pytorch - 如何在没有 cuda_visible_device 的情况下使用 Pytorch 分配多 GPU
- sql - 如果第二个表为空,则在匹配行或全部上的 SQL 连接表
- javascript - POST 中的表单正文以 URL 参数结尾?
- java - Kotlin 数据类中的私有成员变量
- reactjs - 在字符串中引入反应元素
- excel - 防止 Excel 工作簿在计算机之间复制