【问题标题】:convert array that contains object to string将包含对象的数组转换为字符串
【发布时间】:2014-04-25 05:34:35
【问题描述】:

我在$result1 = implode(' ',$result1)时遇到错误

我使用 2 个查询并希望将结果合并为一个,这是我的查询:

if($stmt->execute()){
    $user = $stmt->get_result();
    while ($obj = $user->fetch_object()) {
         $result1[] = $obj;
    }

}

if($stmt->execute()){
    $user = $stmt->get_result();
    while ($obj = $user->fetch_object()) {
         $result2[] = $obj;
    }

}
  • 在此处将 $result1 和 result2 转换为字符串
  • 我需要 $result1 和 result2

    '[{ "uId":"1", "firstName":"James", "lastName":"Bond" }]'

以便它可以在下面的代码中运行。

$arr1 = json_decode($result1,true);
$arr2 = json_decode($result2,true);
$arr1[0]['task'] = $arr2;
$finalJSON = json_encode($arr1);
echo $finalJSON;

【问题讨论】:

  • 任何时候你提到你有一个错误,请包括你收到的实际错误。那是什么?
  • 为什么需要将你的对象编码成 json 并将其解码回数组?

标签: php json


【解决方案1】:

$result1$result2 已经是数组

删除以下行:

$arr1 = json_decode($result1,true);
$arr2 = json_decode($result2,true);

要么将fetch_object 更改为fetch_array

或将$arr1[0]['task'] = $arr2; 更改为$arr1[0]->task = $arr2;不要同时更改)。

【讨论】:

  • 不能在 $result1[0]->task = $result2; 中使用字符串偏移量作为数组;
  • @user3522457 $result1 一开始应该是一个数组,最后你只需要使用json_encode ....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多