首页 > 解决方案 > 从表中获取关联数组中元素的值

问题描述

$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

怎么了?

标签: phpmysql

解决方案


    $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符合预期


推荐阅读