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 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口