Home > Back-end >  How to target another value of the same object?
How to target another value of the same object?

Time:02-18

I have an object:

{
    "id": "GRP-25",
    "text": "All Areas",
    "groupid": 0,
    "leaf": false,
    "qtip": "Common",
    "link": null,
    "helplink": null,
},

Here I'm changing the value of ID but I'm trying to change it only if leaf is true. How do I target the value of a leaf into the if statement?

array_walk_recursive($result, function (&$v, $k) { 
    if($k == 'id'){ 
        $v ='GRP-'.$v; 
    }    
});

CodePudding user response:

array_walk_recursive cannot know the value of leaf. You could create a recursive function to change the value of id from the leaf value:

function changeLeafId(array &$data)
{
    foreach ($data as $k => $v) 
    {
        // recursive call 
        if (is_array($v)) {
            changeLeafId($data[$k]);
            continue;
        }

        // update 'id' from 'leaf'
        if ($k == 'id' && $data['leaf'] ?? false) {
            $data[$k] = 'GRP-' . $v;
        }
    }
}

changeLeafId($result);

You can see the result with sample data : https://3v4l.org/Ss584

CodePudding user response:

I don't think you will be able to do that with array walk, I would be inclined to use a foreach

something along these lines

foreach ($results as &$result) {
  if ($result->leaf == true) {
    $result->id = 'GRP-'.$result->id; 
  }
}

Assuming here you did json_decode as objects, otherwise if you are doing json_decode as arrays, then you will need to change the -> to []

  • Related