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 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面