0

I have been looking or a way to change an objects key name with no success as of yet. I need to be able to parse ALL through the keys in the resulting set, check the name of the key, and assign it a new key name (NOT VALUE) if the name of the key matches a variable $name. I will include my code below:

$infocusArray = array();

 if($result = $conn->query($query))
    
    // Start
    while($row = mysqli_fetch_assoc($result)) {
        array_push($infocusArray, $row);

    };

    foreach($row as $key => $element){
        echo $key; => outputs key names
    };
    
    file_put_contents('data.json', json_encode($infocusArray));
    echo count($infocusArray);
}

data.json result of json_encode($infocusArray):

[
  {
    "id": "ai-101010",
    "sector": "guidance",
    "date": "10-11-2030"
  },
{
    "id": "ai-191011",
    "sector": "airfield",
    "date": "03-01-2023"
  }
]

The dataset I am working with is much larger however I am removing most items for simplicity sake.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Moorsie
  • 31
  • 3
  • It's not clear what you want to do? What is your expected output? Where do you expect the variable `$name` to be used? – Nick Apr 26 '22 at 05:03
  • @Nick The expected output would be a new json encoded file with keys changed to desired values. For example: the key "id" could be changed to "user_id". The $name variable was just a placeholder meant to represent the name of the key you want to change (such as "id") – Moorsie Apr 26 '22 at 15:08
  • Are you able to change the column alias in the SELECT clause of your query? That's the simplest, most efficient way to handle this. @Moo – mickmackusa May 31 '22 at 01:36

1 Answers1

1

There is a simple solution for updating key of any object. You have to store the value of object with new and unset old one.

// Start
while($row = mysqli_fetch_assoc($result)) {

    $row->new_Key = $row->old_key;
    unset($row->old_key);
    array_push($infocusArray, $row);
};