dongliang7545 2016-06-10 16:41
浏览 30
已采纳

从数组合并json然后重新创建数组

I have an array as follows

Array
(
    [photo] => Array
        (
            [0] => {"file_name":"Penguins.jpg", "content_type": "image/jpeg", "tmp_path": "/var/www/servergreek.com/public_html/www/imgscript/tmp/0048699176"}
            [1] => {"file_name":"Penguins.jpg", "sha256" : "7e5bdd023b6cf21efe42a8ec90bc1993fc853980d4b564688e5ac2d28c64223c" , "size" : "777835"}
            [2] => {"file_name":"sample.png", "content_type": "image/png", "tmp_path": "/var/www/servergreek.com/public_html/www/imgscript/tmp/0048699177"}
            [3] => {"file_name":"sample.png", "sha256" : "e6aa1bf1cdb7ca546576cecd61973939be4f1dc8cec3a4f3b49b31d8f60e202f" , "size" : "278383"}
        )

    [submit] => Upload
)

I want to create an array as follows

Array
(
    [photo] => Array
        (
            [0] => {"file_name":"Penguins.jpg", "content_type": "image/jpeg", "tmp_path": "/var/www/servergreek.com/public_html/www/imgscript/tmp/0048699176" , "sha256" : "7e5bdd023b6cf21efe42a8ec90bc1993fc853980d4b564688e5ac2d28c64223c" , "size" : "777835"}

            [1] => {"file_name":"sample.png", "content_type": "image/png", "tmp_path": "/var/www/servergreek.com/public_html/www/imgscript/tmp/0048699177" , "sha256" : "e6aa1bf1cdb7ca546576cecd61973939be4f1dc8cec3a4f3b49b31d8f60e202f" , "size" : "278383"}
        )

    [submit] => Upload
)
  • 写回答

4条回答 默认 最新

  • douchuituo3032 2016-06-10 18:37
    关注

    Here is a solution which uses array_reduce to build a map with decoded JSON objects, keyed by their file_name values, and then applies array_map to convert the objects in that map back to JSON strings.

    The intermediate array_values turns the associative array into an indexed array:

    $data['photo'] = array_map('json_encode', array_values(array_reduce($data['photo'], 
        function($dict, $json) {
            $obj = json_decode($json, true);
            $key = $obj['file_name'];
            if (!isset($dict[$key])) $dict[$key] = [];
            $dict[$key] += $obj; // merging arrays with plus operator
            return $dict;
        }, []))
    );
    

    This solution does not necessitate that two related JSON strings are consecutive. It will work if the array is in any order. It also works if there would be more than two JSON strings with the same file_name property, joining whatever other properties are in those extra JSON strings.

    See it run on eval.in.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析