从表中获取关联数组中元素的值

时间:2018-11-29 08:39:35

标签: php mysql

$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

怎么了?

2 个答案:

答案 0 :(得分:1)

    $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

答案 1 :(得分:0)

先执行json_decode,然后直接访问密钥。

$arrx = json_decode($arrx['map']);

要访问b1

echo $arrx->b1;

您更新后的代码段如下所示,

$sql = "select map from params where what = 'artb'";
$st = $db->prepare($sql);
$st->execute();
$arrx = $st->fetch();

foreach($arrx as $key => $el){
    $elMap = json_decode($el['map']);
    echo $elMap->b1;
}