Skip to content
Advertisement

How can I create new array from this JSON response?

I am really struggling to create a new array from this response, I don’t know where and how to start or to do it:

{
    "fruits": [
        {
            "name": "Bananas",
            "pieces": 2469429
        },
        {
            "name": "Oranges",
            "pieces": 1576890
        },
        {
            "name": "Lemons",
            "pieces": 5645318
        }
    ],
    "size": [
        {
            "size": "5000-10,000 eaters",
            "pieces": 17008533
        },
        {
            "size": "100-500 eaters",
            "pieces": 23473914
        },
        {
            "size": "10,001+ eaters",
            "pieces": 68086139
        }
    ],
    "SizeAndFruit": [
        {
            "size": "100-500 eaters",
            "pieces": 226636,
            "name": "Bananas"
        },        
        {
            "size": "5000-10,000 eaters",
            "pieces": 249004,
            "name": "Bananas"
        },
        {
            "size": "10,001+ eaters",
            "pieces": 727829,
            "name": "Bananas"
        },
        {
            "size": "100-500 eaters",
            "pieces": 416310,
            "name": "Lemons"
        },
        {
            "size": "5000-10,000 eaters",
            "pieces": 488711,
            "name": "Lemons"
        },
        {
            "size": "10,001+ eaters",
            "pieces": 2340652,
            "name": "Lemons"
        },
        {
            "size": "100-500 eaters",
            "pieces": 217037,
            "name": "Oranges"
        },
        {
            "size": "5000-10,000 eaters",
            "pieces": 71779,
            "name": "Oranges"
        },
        {
            "size": "10,001+ eaters",
            "pieces": 201729,
            "name": "Oranges"
        }
    ]
}

I want to get this new structure/array:

{
    "newArray": [
    {
        "name": "Bananas",
        "totalResults": 2469429,
        "sortedResults": [
            {
                "size": "100-500 eaters",
                "pieces": 226636
            },
            {
                "size": "5000-10,000 eaters",
                "pieces": 249004
            },
            {
                "size": "10,001+ eaters",
                "pieces": 727829
            }
        ]
    },
    {
        "name": "Oranges",
        "totalResults": 1576890,
        "sortedResults": [
            {
                "size": "100-500 eaters",
                "pieces": 217037
            },
            {
                "size": "5000-10,000 eaters",
                "pieces": 71779
            },
            {
                "size": "10,001+ eaters",
                "pieces": 201729
            }
        ]
    },
    {
        "name": "Lemons",
        "totalResults": 5645318,
        "sortedResults": [
            {
                "size": "100-500 eaters",
                "pieces": 416310
            },
            {
                "size": "5000-10,000 eaters",
                "pieces": 488711
            },
            {
                "size": "10,001+ eaters",
                "pieces": 2340652
            }
        ]
    }
]
}

How can I make for each fruit to add all sizes as subarray from the sizeAndFruit as the example above? After that each fruit has to be row in a table, that’s why I need to get this new array? Please let me know if you have any suggestions or any extra questions I will be glad to explain more if needed. Thank you very much!


Edit for David: How about if we always order them by size? Here is the snippet: pastecode.io/s/t82n19x4 so when the order is like this. So, to order them by size as it is now on David’s reply, because if these are mixed then they order as they go instead by 100-500 5001-10000 10,000+ they go 10.000+ 100-500 5001-1000, etc. Thank you!

Advertisement

Answer

The below codes reads your inputs and turns it into your desired output (including sorting by size):

<?php

$inputContents = file_get_contents(__DIR__ . '/input.json');
$inputJson = json_decode($inputContents);

$out = [];

foreach ($inputJson->fruits as $fruit) {
    $out[] = [
        'name' => $fruit->name,
        'totalResults' => $fruit->pieces,
        'sortedResults' => [],
    ];
}

foreach ($inputJson->SizeAndFruit as $entry) {
    $newEntry = [
        'size' => $entry->size,
        'pieces' => $entry->pieces,
    ];

    foreach ($out as &$fruit) {
        if ($fruit['name'] === $entry->name) {
            $fruit['sortedResults'][] = $newEntry;
        }
    }
}

/**
 * Get a number of the size from the provided string.
 * 
 * @param string $size
 * 
 * @return int|null
 */
function sizeStringToNumber(string $size): ?int
{
    $sizes = [
        '100-500 eaters' => 100,
        '5000-10,000 eaters' => 5000,
        '10,001+ eaters' => 10000,
    ];

    if (isset($sizes[$size])) {
        return $sizes[$size];
    }

    throw new Exception('Unknown size: ' . $size);
}

/**
 * Sort the `sortedResults` array by `size` in ascending order.
 */
foreach ($out as &$fruit) {
    usort($fruit['sortedResults'], function ($a, $b) {
        $aSize = sizeStringToNumber($a['size']);
        $bSize = sizeStringToNumber($b['size']);
        return $aSize <=> $bSize;
    });
}


$outArray = [
    'newArray' => $out,
];
$outJson = json_encode($outArray, JSON_PRETTY_PRINT);

print_r($outJson);

Prints as:

{
    "newArray": [
        {
            "name": "Bananas",
            "totalResults": 2469429,
            "sortedResults": [
                {
                    "size": "100-500 eaters",
                    "pieces": 226636
                },
                {
                    "size": "5000-10,000 eaters",
                    "pieces": 249004
                },
                {
                    "size": "10,001+ eaters",
                    "pieces": 727829
                }
            ]
        },
        {
            "name": "Oranges",
            "totalResults": 1576890,
            "sortedResults": [
                {
                    "size": "100-500 eaters",
                    "pieces": 217037
                },
                {
                    "size": "5000-10,000 eaters",
                    "pieces": 71779
                },
                {
                    "size": "10,001+ eaters",
                    "pieces": 201729
                }
            ]
        },
        {
            "name": "Lemons",
            "totalResults": 5645318,
            "sortedResults": [
                {
                    "size": "100-500 eaters",
                    "pieces": 416310
                },
                {
                    "size": "5000-10,000 eaters",
                    "pieces": 488711
                },
                {
                    "size": "10,001+ eaters",
                    "pieces": 2340652
                }
            ]
        }
    ]
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement