【问题标题】:create an array based on two table id's in php根据php中的两个表ID创建一个数组
【发布时间】:2016-10-22 21:37:55
【问题描述】:

我有两张桌子。一个是“demo”,另一个是“like”。

我正在使用 json_encode 将值数组转换为 json 格式。

演示有:

[{ 'id': 1, 'like_id': 2, 'name': 'hero' }, { 'id': 2, 'like_id': 1, 'name': 'villain' }]

喜欢有:

[{ 'id': 1, 'movie'': 'castle' }, {'id': 2, 'movie' : 'superman' }]

我要新建一个json数据如下:

[{ 'id': 1, 'like_id': [{'id': 2, 'movie' : 'superman'}], 'name': 'hero'},
 { 'id': 2, 'like_id': [{'id': 1, 'movie': 'castle'}], 'name': 'villain'}]

搜索了一段时间后,我想我可能需要递归函数。但我不确定在这种情况下我该怎么写。

这是我尝试过的:

$pages = array();

$demo = Object('demo');
$like = Object('like');

foreach ($demo as $d) {
    foreach ($like as $l) {
        $response = array(
           'id' => $d['id'],
           'like_id' => array(
                 'id' => $l['id'],
                 'movie' => $l['movie']
           ),
           'name' => $d['name']
        );
        array_push($pages, $response);
     }
  }
$res = json_encode($pages);
echo $res;

【问题讨论】:

  • 你不需要递归。只是嵌套了foreach 循环。
  • 为什么在结果中需要like_id 中的数组? Demo 中只有一个 ID 号,所以应该将其替换为 Like 中的对象。
  • @Barmar 我尝试了嵌套的 foreach。但它会增加更多次数并打印结果。
  • 显示您尝试过的内容。我们还能如何帮助您了解您的错误?
  • 为什么要打印结果?您只是使用循环创建一个新数组,并在完成后调用json_encode

标签: php arrays json recursion multidimensional-array


【解决方案1】:

问题在于您没有检查$like 中的id 是否与$demo 中的like_id 匹配,因此您正在生成所有组合。

foreach ($demo as $d) {
    foreach ($like as $l) {
        if ($d['like_id'] == $l['id']) {
            $response = $d;
            $response['like_id'] = array(array('id' => $l['id'],
                                               'movie' => $l['movie'])
                                         );
            array_push($pages, $response);
        }
    }
}

DEMO

【讨论】:

  • $response = $d;似乎不起作用。但是,当我尝试添加为 $response = array ('id' => 1, name => 'hero');。这再次对所有可能的组合重复。如果我如上所述尝试, $response['like_id'] 将不起作用。有什么建议吗?
  • 我缺少一个右大括号,所以它根本不会运行。我猜你在错误的地方添加了它。我也忘了把like_id 对象放在一个额外的数组级别(我仍然不明白你为什么有那个)。我纠正了这两个问题,现在代码可以工作了,请参阅 ideone.com 演示。
【解决方案2】:

使用json_decodestr_replace(为正确解码做准备)函数的解决方案:

$demo = "[{ 'id': 1, 'like_id' : 2, 'name': 'hero' }, { 'id': 2, 'like_id': 1, 'name': 'villain' }]";
$likes = "[{ 'id': 1, 'movie': 'castle' }, {'id': 2, 'movie' : 'superman' }]";

$demo_objects = json_decode(str_replace("'",'"',$demo));
$like_objects = json_decode(str_replace("'",'"',$likes));
foreach ($demo_objects as $o) {
    foreach ($like_objects as $l) {
        if ($l->id == $o->like_id) $o->like_id = [$l];
    }

}

print_r(json_encode($demo_objects));

输出:

[
  {"id":1,"like_id":[{"id":2,"movie":"superman"}],"name":"hero"},
  {"id":2,"like_id":[{"id":1,"movie":"castle"}],"name":"villain"}
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2020-07-04
    • 2018-06-20
    相关资源
    最近更新 更多