2
\$\begingroup\$

I made a program that converts JSON to a PHP array and checks every value of the multidimensional array with a loop and if a value matches certain values then it deletes that key and value and converts it back to JSON. I am trying to make this with less code.

I use a nested foreach loop to check every element in the array. I give it condition like if value == 0 or empty string or null then delete it but it occupies too many lines of code. It is not a good method for too many multidimensional array so I was looking for a better solution.

This is my JSON:

{
"UniqueId": "PO3589472",
"FareType": 2,
"BookedBy": "Api ",
"OrderBy": "Api ",
"ClientBalance": 0,
"Error": null,
"Success": true,
"TktTimeLimit": "2022-08-10T14:11:45",
"Category": 21,
"Status": 21,
"RefundMethod": 1,
"TravelItinerary": {
    "ItineraryInfo": {
        "ItineraryPricing": {
            "BaseFare": 8469250,
            "ServiceTax": 0,
            "TotalTax": 993000,
            "TotalFare": 9462250,
            "TotalCommission": 0,
            "Currency": "IRR"
        },
        "CustomerInfoes": [
            {
                "Customer": {
                    "Gender": 0,
                    "PassengerType": 1,
                    "PassportNumber": "",
                    "NationalId": "1829961233",
                    "Nationality": "IR",
                    "DateOfBirth": "1996-07-08T00:00:00",
                    "PassportExpireDate": "0001-01-01T00:00:00",
                    "PassportIssueCountry": "IR",
                    "PassportIssueDate": "2022-08-10T00:00:00",
                    "PaxName": {
                        "PassengerFirstName": "MAJID",
                        "PassengerMiddleName": null,
                        "PassengerLastName": "MAJIDIFAR",
                        "PassengerTitle": 0
                    }
                },
                "ETickets": "8151405444745",
                "ETicketNumbers": [
                    {
                        "ETicketNumber": "8151405444745",
                        "EticketStatus": 1,
                        "IsRefunded": false,
                        "DateOfIssue": "2022-08-10T13:58:47",
                        "AirlinePnr": "TXNXM",
                        "TotalRefund": 0
                    }
                ]
            }
        ],
        "ReservationItems": [
            {
                "AirEquipmentType": "737",
                "AirlinePnr": "TXNXM",
                "ArrivalAirportLocationCode": "ABD",
                "ArrivalDateTime": "2022-08-17T23:25:00",
                "ArrivalTerminal": "",
                "Baggage": "20KG",
                "DepartureAirportLocationCode": "THR",
                "DepartureDateTime": "2022-08-17T22:05:00",
                "DepartureTerminal": "Terminal 4",
                "FlightNumber": "3750",
                "JourneyDuration": "01:20",
                "JourneyDurationPerMinute": 0,
                "MarketingAirlineCode": "EP",
                "OperatingAirlineCode": "EP",
                "ResBookDesigCode": "Y",
                "StopQuantity": 0,
                "IsCharter": false,
                "TechnicalStops": [],
                "IsReturn": false,
                "CabinClassCode": 1
            }
        ],
        "TripDetailPtcFareBreakdowns": [
            {
                "PassengerTypeQuantity": {
                    "PassengerType": 1,
                    "Quantity": 1
                },
                "TripDetailPassengerFare": {
                    "BaseFare": 8469250,
                    "ServiceTax": 0,
                    "Tax": 993000,
                    "TotalFare": 9462250,
                    "Commission": 0,
                    "Currency": "IRR"
                }
            }
        ],
        "PhoneNumber": "09359276735",
        "Email": "info@iran-tech.com",
        "ItineraryFareFamily": null
    },
    "BookingNotes": [],
    "Services": []
},
"ValidatingAirlineCode": "EP",
"DirectionInd": 1,
"OnlineCheckIn": false,
"AirRemark": [],
"curl_error": false}

this is my php code

<?php
$jsondata = file_get_contents("test_php.json");
$json = json_decode($jsondata, true);


foreach($json as $keys1 => $values1){
    if($values1 == 0 || $values1 == "" || $values1 == "Api " || !isset($values1) ){
        unset($json[$keys1]);
    }else{
        if(is_array($values1)){
            foreach($values1 as $keys2 => $values2){
                if($values2 == 0 || $values2 == "" || $values2 == "Api " || !isset($values2) ){
                    unset($json[$keys1][$keys2]);
                }else{
                    if(is_array($values2)){
                        foreach($values2 as $keys3 => $values3){
                            if($values3 == 0 || $values3 == "" || $values3 == "Api " || !isset($values3) ){
                                unset($json[$keys1][$keys2][$keys3]);
                            }else{
                                if(is_array($values3)){
                                    foreach($values3 as $keys4 => $values4){
                                        if($values4 == 0 || $values4 == "" || $values4 == "Api " || !isset($values4) ){
                                            unset($json[$keys1][$keys2][$keys3][$keys4]);
                                        }else{
                                            if(is_array($values4)){
                                                foreach($values4 as $keys5 => $values5){
                                                    if($values5 == 0 || $values5 == "" || $values5 == "Api " || !isset($values5) ){
                                                        unset($json[$keys1][$keys2][$keys3][$keys4][$keys5]);
                                                    }else{
                                                        if(is_array($values5)){
                                                            foreach($values5 as $keys6 => $values6){
                                                                if($values6 == 0 || $values6 == "" || $values6 == "Api " || !isset($values6) ){
                                                                    unset($json[$keys1][$keys2][$keys3][$keys4][$keys5][$keys6]);
                                                                }else{
                                                                    if(is_array($values6)){
                                                                        foreach($values6 as $keys7 => $values7){
                                                                            if($values7 == 0 || $values7 == "" || $values7 == "Api " || !isset($values7) ){
                                                                                unset($json[$keys1][$keys2][$keys3][$keys4][$keys5][$keys6][$keys7]);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
    }
}
$path = "test_php(final).json";
$converter = json_encode($json, JSON_PRETTY_PRINT);
// print_r($v);
$open = fopen($path, 'w');
fwrite($open, $converter);
fclose($open);
// print_r($json);
?>
\$\endgroup\$
0

2 Answers 2

1
\$\begingroup\$

Use recommended/idiomatic spacing

Mick has already answered the main question about reducing the code by utilizing a recursive function. Notice in that sample code that there is a space following keywords like foreach and if, as well as one space between a closing parenthesis and the opening brace. Take for example the foreach and if statements on the first two lines of the function:

foreach ($input as &$value) { 
    if (is_array($value)) {  

This is common in idiomatic PHP code, and is recommended by the PHP Standards Recommendations guide PSR-12. The original code does not have such spaces - for example:

foreach($json as $keys1 => $values1){
    if($values1 == 0 || $values1 == "" || $values1 == "Api " || !isset($values1) ){

Writing to a file can be a single line instead of three

It is fine to call fopen(), fwrite() and fclose(), though the same can be achieved by calling file_put_contents().

 file_put_contents($path, $converter);

This approach can be slightly slower so if performance is a concern then it may be wise to keep the current tactic of calling the three functions instead.

\$\endgroup\$
0
4
\$\begingroup\$

Use a recursive approach to filter the array of indeterminate depth.

Shown here: How to run array_filter recursively in a PHP array?

Then just build in whatever logic you wish to filter by.

Below will keep any "truthy" value that is not "Api ".

Notice that it will consequently remove empty arrays -- though you didn't explicitly ask for this -- because empty arrays are "falsey".

Code: (Demo)

$array = json_decode($json, true);

function array_filter_recursive(array $input): array 
{ 
    foreach ($input as &$value) { 
        if (is_array($value)) { 
            $value = array_filter_recursive($value); 
        } 
    } 
    
    return array_filter($input, fn($v) => $v && $v !== 'Api '); 
} 

var_export(array_filter_recursive($array));
\$\endgroup\$
2

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.