0

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
)
1
  • Do they always come in ordered pairs like your example? Commented Jun 10, 2016 at 16:56

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice one thing though. The resulting array is multi-demiensional. It would be okay if its indexed
Thanks, @Abiodun, I added an intermediate call to array_values to turn the associative array into an indexed array.
Exactly what i needed...Thx
1
$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'];

// This is your given array

$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);

1 Comment

The two arrays are always the same. You probably wanted ++$i instead of $i++.
1
<?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);

?>

This works on php 7, tested on sandbox.onlinephpfunctions.com:

I hope this helped you, instead this could inspired you and other.

2 Comments

Values are lost with this code. Where did "sha256" go? You need to merge entries, not unset them.
You're rigth @trincot, didn't see merging effect. My bad.
1

Your Structure

[
    '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'
];

Desired Output

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

Code

    <?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;
    }
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.