在PHP变量中存储多个JSON对象值

时间:2018-07-06 15:51:49

标签: php json object

我正在尝试将单个对象的多个json值存储在php变量中,但到目前为止仍未成功。当我尝试下面的代码时,它将存储对象的最后一个值,但不能同时存储两个值。

$_POST = json_decode(file_get_contents('php://input'));

foreach($_POST->repliesCounts as $replies_counts)
{
$replies_counts_userid = $replies_counts->userId . " | ";
$replies_counts_repliescount = $replies_counts->repliesCount . " | ";
}

这是JSON字符串:

 "repliesCounts": 
  [
    {
        "userId": 789,
        "repliesCount": 4
    },
    {
        "userId": 111,
        "repliesCount": 3
    }
  ]

我的问题是,如何将两个值集存储在一个变量中?最好用|隔开符号或类似内容。

2 个答案:

答案 0 :(得分:3)

您可以使用第二个参数json_decode true返回一个关联数组而不是对象。使用array_column从数组中提取一列并将其转换为简单数组。使用implode来连接简单数组。

$str = '{"repliesCounts": [{ "userId": 789,"repliesCount": 4},{"userId": 111,"repliesCount": 3}]}';
$arr = json_decode($str, true);

//Make associative array into a simple array
$replies_counts_userid = array_column( $arr['repliesCounts'], 'userId' );
$replies_counts_repliescount = array_column( $arr['repliesCounts'], 'repliesCount' );

//implode array
$replies_counts_userid = implode(' | ', $replies_counts_userid);
$replies_counts_repliescount = implode(' | ', $replies_counts_repliescount);

这将导致

$replies_counts_userid = '789 | 111';
$replies_counts_repliescount = '4 | 3';

答案 1 :(得分:1)

$replies_counts_userid = $replies_counts->userId . " | ";

此行用新值完全替换了旧值。您还需要在这里串联:

$replies_counts_userid .= $replies_counts->userId . " | ";

应该工作。 (在.之前注意=