【问题标题】:Keep getting "Array" from fetching decoded JSON data?继续从获取解码的 JSON 数据中获取“数组”?
【发布时间】:2018-12-18 20:05:42
【问题描述】:

当我对从 mysql 数据库获取的 json 数据进行编码时,我得到了这个:

[{"userid":"11","postid":"12"},{"userid":"13","postid":"12"},{"userid":"16","postid":"12"}]

我试图只获取这样的用户 ID:11, 13, 16

解码 json 数据给我一个输出:Array。没有别的了。当我var_dump 这是我的结果:

array(3) { 
        [0]=> array(2) { 
                    ["userid"]=> string(2) "11" 
                    ["postid"]=> string(2) "12" 
                } 
        [1]=> array(2) { 
                    ["userid"]=> string(2) "13" 
                    ["postid"]=> string(2) "12" 
                } 
        [2]=> array(2) { 
                    ["userid"]=> string(2) "16" 
                    ["postid"]=> string(2) "12" 
                } 

所以我知道有数据存在,只是由于某种原因没有显示。

这是我的查询的样子:

if(isset($_POST['postuserid'])){
    $uid = $_POST['postuserid'];

    $ssql = "SELECT * FROM foodid WHERE postid=$uid"; 
    $rresult = mysqli_query($db,$ssql); 
    while ($lrow = mysqli_fetch_assoc($rresult)){ 
        $ret[] = $lrow;
        $postjson = json_encode($ret);  
        $decode_postid = json_decode($postjson, true);
        $new_postid = $decode_postid;
    } 
    var_dump($new_postid);
    die($new_postid);
    // die($new_postid['userid']); is what I need along with all data userid fetched.

}

当我对 json 数据进行编码时,这是否有效,但在我解码 json 数据时无效?

【问题讨论】:

  • $new_postid 在 while 循环中被加载,但每次循环时你都写完了

标签: php mysql arrays json mysqli


【解决方案1】:

尝试映射这些结果:

$new_postid = $decode_postid;
$new_postid = array_map(function($item){
    return $item['userid'];
}, $new_postid);

var_dump($new_postid);

输出

数组(3){ [0]=> 字符串(2)“11” 1=> 字符串(2)“13” [2]=> 字符串(2)“16” }

如果需要输出为字符串,使用implode函数即可

die(implode(',',$new_postid));

http://php.net/manual/en/function.array-map.php

【讨论】:

  • 谢谢,这就是我得到的结果,但我期待die($new_postid) 的这些结果:11、13、16。只是数字
  • 没问题。 IMO 使用语言构造时会更好。代码变得更干净,更容易维护。如果您有更好的方法,请避免使用子字符串和循环。
  • 我同意!同样,我计划将数字转换为名称。 IE。 “比利”代替“11”。我必须想办法用 php 查询表来做到这一点。
  • 我还有一个问题,说如果我也想要postid。我会在这里做同样的事情,只是改变变量名吗?
【解决方案2】:

您是否要从 die 函数中取出该数组?它只能接受一个字符串或整数。

http://php.net/manual/en/function.exit.php

你的数组在那里......只需执行以下操作:

$ids = '';
foreach ($new_postid as $post) {
    $ids .= $post['userid'] . ',';
}
$ids = rtrim($ids,',');
die($ids);

【讨论】:

  • 是的,这就是我要找的!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 1970-01-01
相关资源
最近更新 更多