【问题标题】:Merge json from array and then recreate array从数组合并json然后重新创建数组
【发布时间】:2016-06-11 07:45:26
【问题描述】:

我有一个数组如下

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
)

我想创建一个数组如下

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
)

【问题讨论】:

  • 他们总是像你的例子那样成对出现吗?

标签: php arrays json


【解决方案1】:

这是一个解决方案,它使用array_reduce 来构建一个包含解码后的 JSON 对象的映射,由它们的 file_name 值作为键,然后应用 array_map 将该映射中的对象转换回 JSON字符串。

中间的array_values把关联数组变成索引数组:

$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;
    }, []))
);

此解决方案不需要两个相关的 JSON 字符串是连续的。如果数组按任何顺序排列,它将起作用。如果有两个以上的 JSON 字符串具有相同的 file_name 属性,它也可以工作,加入这些额外 JSON 字符串中的任何其他属性。

查看它在eval.in 上运行。

【讨论】:

  • 一件好事。生成的数组是多维度的。如果它被索引就可以了
  • 谢谢@Abiodun,我添加了对array_values 的中间调用,将关联数组转换为索引数组。
  • 正是我需要的...谢谢
【解决方案2】:
$array = ['photo'=>
    ['{"file_name":"Penguins.jpg", "content_type": "image/jpeg", "tmp_path": "/var/www/servergreek.com/public_html/www/imgscript/tmp/0048699176"}','{"file_name":"Penguins.jpg", "sha256" : "7e5bdd023b6cf21efe42a8ec90bc1993fc853980d4b564688e5ac2d28c64223c" , "size" : "777835"}','{"file_name":"sample.png", "content_type": "image/png", "tmp_path": "/var/www/servergreek.com/public_html/www/imgscript/tmp/0048699177"}','{"file_name":"sample.png", "sha256" : "e6aa1bf1cdb7ca546576cecd61973939be4f1dc8cec3a4f3b49b31d8f60e202f" , "size" : "278383"}'],

    'submit'=> 'Upload'];

// 这是你给定的数组

$result_array = [
    'photos' => [],
    'submit' => 'Upload'
    ];
for($i=0; $i < count($array['photo'])-1; $i++){
    $array_one = json_decode($array['photo'][$i], true);
    $array_two = json_decode($array['photo'][$i++], true);
        array_push($result_array['photos'], array_merge($array_one, $array_two));
}
print_r($result_array);

【讨论】:

  • 这两个数组总是一样的。您可能想要++$i 而不是$i++
【解决方案3】:
<?php

$array = 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"}',
                '4' => '{"file_name":"Penguins.jpg", "content_type": "image/jpeg", "tmp_path": "/var/www/servergreek.com/public_html/www/imgscript/tmp/0048699176"}',
                '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'
); // Your array representation

function distinct($item, $key, $array) {
    $file_name = json_decode($item)->file_name; // saving file name
    $find_count = 0; // initializing found count
    
    foreach($array['photo'] as $i => $json) {
        $json = json_decode($json);
        
        if($json->file_name == $file_name) {
            if($find_count >= 1) {
                unset($array['photo'][$i]);
            }
            if(property_exists($json, 'content_type')) { // This keep the json with a content type property
                $find_count++;
            }
        }
    }
}

array_walk_recursive($array['photo'], 'distinct', $array);

var_dump($array);

?>

这适用于 php 7,在 sandbox.onlinephpfunctions.com 上测试:

我希望这对您有所帮助,而不是这可以启发您和其他人。

【讨论】:

  • 使用此代码会丢失值。 "sha256"去哪儿了?您需要合并条目,而不是取消设置它们。
  • 你是正确的@trincot,没有看到合并效果。我的错。
【解决方案4】:

你的结构

[
    'photo'  => [
        '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"}',
        '4' => '{"file_name":"Penguins.jpg", "content_type": "image/jpeg", "tmp_path": "/var/www/servergreek.com/public_html/www/imgscript/tmp/0048699176"}',
        '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'
];

期望的输出

[
    [photo] => [
        [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
]

代码

    <?php
    $array = getYourArrayStrcuture(); // you don't need this as you already have this array strcuture
    $photoByName = getArrayByFileName($array); // Get array back with file name as key
    $result = convertArrayToJson($photoByName,$array); // convert array to json
    echo "<pre>";
    print_r($result);

    /**
     * Convert array to json
     */
    function convertArrayToJson($photoByName,$array)
    {
        $result = [];
        foreach($photoByName as $key=>$value){
            $result[] = json_encode($value);
        }
        $array['photo'] = $result;
        return $array;
    }

    /**
     * Get array back with file name as key
     */
    function getArrayByFileName($array)
    {
        $photoArray = $array['photo'];
        $photoByName = [];

        foreach ($photoArray as $photo) {
            $itemJsonToArray = json_decode($photo, true);
            if (!isset($photoByName[ $itemJsonToArray['file_name'] ])) {
                $photoByName[ $itemJsonToArray['file_name'] ] = $itemJsonToArray;
            } else {
                $photoByName[ $itemJsonToArray['file_name'] ] = array_merge($photoByName[ $itemJsonToArray['file_name'] ], $itemJsonToArray);
            }
        }

        return $photoByName;
    }

    /**
     * You don't need this as you already have this array structure
     */
    function getYourArrayStrcuture()
    {
        $yourArrayStructure = [
            'photo'  => [
                '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"}',
                '4' => '{"file_name":"Penguins.jpg", "content_type": "image/jpeg", "tmp_path": "/var/www/servergreek.com/public_html/www/imgscript/tmp/0048699176"}',
                '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'
        ];

        return $yourArrayStructure;
    }
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    相关资源
    最近更新 更多