skip to Main Content

I’m using PHP to pull data out from a database. The response is a multi dimensional JSON and I need to dynamically delete part of the data, here’s the structure of:

{
    "success": true,
    "data": [
        {
            "Name": "Jane",
            "Id": "3473-45413-1657445",
            "Alias": "Doe",
            "UDID": "654984-6548648-1651684",
            "KEY": "asd-456-ghj",
            "params": [
                {
                    "Type": "K12",
                    "Model": "53-DDL",
                    "UnitCost": 55.5,
                    "QTY": 1,
                    "Amount": 55.5,
                    "Spec": null
                },
                {
                    "Type": "K11",
                    "Model": "55-604",
                    "UnitCost": 55.5,
                    "QTY": 1,
                    "Amount": 55.5,
                    "Spec": null
                }
            ],
            "level": 0,
            "Total": 55.5,
            "Member": null,
            "LogTime": "2023-12-25 12:40:59",
            "OP1": "Jack",
            "OP2": "Danny",
            "OP3": "Paul",
            "Attempt": 1,
            "Location": "LA"
        },
        {
            "Name": "Jane",
            "Id": "3473-45413-1657445",
            "Alias": "Doe",
            "UDID": "654984-6548648-1651684",
            "KEY": "asd-456-ghj",
            "params": [
                {
                    "Type": "K12",
                    "Model": "53-DDL",
                    "UnitCost": 55.5,
                    "QTY": 1,
                    "Amount": 55.5,
                    "Spec": null
                },
                {
                    "Type": "K11",
                    "Model": "55-604",
                    "UnitCost": 55.5,
                    "QTY": 1,
                    "Amount": 55.5,
                    "Spec": null
                }
            ],
            "level": 0,
            "Total": 55.5,
            "Member": null,
            "LogTime": "2023-12-25 12:40:59",
            "OP1": "Jack",
            "OP2": "Danny",
            "OP3": "Paul",
            "Attempt": 1,
            "Location": "LA"
        },
        {
            "Name": "Jane",
            "Id": "3473-45413-1657445",
            "Alias": "Doe",
            "UDID": "654984-6548648-1651684",
            "KEY": "asd-456-ghj",
            "params": [
                {
                    "Type": "K12",
                    "Model": "53-DDL",
                    "UnitCost": 55.5,
                    "QTY": 1,
                    "Amount": 55.5,
                    "Spec": null
                },
                {
                    "Type": "K11",
                    "Model": "55-604",
                    "UnitCost": 55.5,
                    "QTY": 1,
                    "Amount": 55.5,
                    "Spec": null
                }
            ],
            "level": 0,
            "Total": 55.5,
            "Member": null,
            "LogTime": "2023-12-25 12:40:59",
            "OP1": "Jack",
            "OP2": "Danny",
            "OP3": "Paul",
            "Attempt": 1,
            "Location": "LA"
        }

    ],
    "code": 0,
    "msg": "Success",
    "count": 3
}

What I need to delete is every second of data[]. What I have tried and works is to decode JSON to array and split the data[] as a new array and then unset every 2nd of it, like below:

$new_arr =  $data['data'];
for ( $i = 1; isset($new_arr[$i]); $i += 2){ 
    unset($new_arr[$i]);
}

Then join the new array with the rest of the original JSON data.

However, I wonder if there is a more elegant way that I can use less code and do it in the fly.
Something like:

$data['data'][$i],$i++,if $i%2 ==0, unset($data['data'][$i])

Which I tried and won’t work. Any lights?

2

Answers


  1. You could use array_filter, and pass the array key:

    $data->data = array_filter($data->data, fn ($k) => $k % 2, ARRAY_FILTER_USE_KEY);
    
    Login or Signup to reply.
  2. One way to acheive this would be to use the array_filter function. This functions takes two parameters: the array, and a callback. The function will return a new array containing only the element that passes the tests provided by the callback.

    The provided callback will also takes two parameters, the current value and the current index, and is expected to returns a boolean. Using this knowledge, you could filter your array by removing the element whose index is divisible by 2, or any other number for that matter.

    $array = [
      'data' => [
        /** ... **/
      ]
    ]
    
    $filteredArray = array_filter($array, function($element, $index) { 
      return $index % 2 !== 0;
    });
    

    In the previous example, I’m using the modulo operator to validate the remainder of the divisition. If the remainder is 0, the index was divisible by 2. In other word, it was the 2nd, 4th, 6th, etc. element. Since we don’t want to keep those element, i’m checking if the remainder was not 0, which indicate that the index was not divisible by 2, hence keeping only the 1st, 3rd, 5th, etc. elements.

    Note that I’m using the longer version of an anonymous function. This could be replace, in php 7.4, with the arrow function, which make the code a little bit cleaner, but harder to read:

    $array = [
      'data' => [
        /** ... **/
      ]
    ]
    
    $filteredArray = array_filter($array, fn($element, $index) => $index % 2 !== 0);
    

    P.S. This code is untested and might contains bug. Use this example as a reference to help you understand the concept, not as a working solution.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search