How to change values in a json array

1k Views Asked by At

I have this JSON array from a mysqli query, and I need to change some of the values inside it, before passing it to Datatables.

"released" : 0 should print "No", and "Yes" if value is 1. "sex" : 1 is female, and "sex": 0 is male.

How can I do these string replaces in this array?

[{
    "id": "3",
    "river": "Dirdalselva",
    "pool": "Sone 1",
    "fish": "Sjøørret",
    "date": "2009-06-18",
    "weight": "1300",
    "length": "65",
    "fly": "Dryfly",
    "released": "0",
    "picture": "http:\/\/localhost\/php\/files\/35409ec6762544c55500b32a7ff37ee9.jpeg",
    "sex": "1",
    "user": "Filip"
}

Here's how I get the array:

$myArray = array();
if ($result = $mysqli->query("SELECT * FROM fish")) {

    while($row = $result->fetch_array(MYSQL_ASSOC)) {
        $myArray[] = $row;
    }
    echo json_encode($myArray);
}
2

There are 2 best solutions below

2
On BEST ANSWER

You actually have a PHP array from your mysqli query. So you should be able to just change the values of $row before you assign them to $myArray.

$row['released'] = ($row['released'] == 0) ? 'No' : 'Yes';
$row['sex'] = ($row['sex'] == 0) ? 'Male' : 'Female';
$myArray[] = $row;
1
On

You can use switch statements inside while to achieve this, see below:-

$myArray = array();
if ($result = $mysqli->query("SELECT * FROM fish")) {

    while($rows = $result->fetch_array(MYSQL_ASSOC)) {
        if(is_array($rows)){
            foreach($rows as $row => $value)
            switch(strtolower(trim($row))){
                case 'released':
                    $myArray[] = ($value == 1) ? 'Yes' : 'No';
                    break;
                case 'sex':
                    $myArray[] = ($value == 1) ? 'female' : 'male';
                    break;
                default: 
                    $myArray[] = $value;
                    break;

            }
        }

    }
    echo json_encode($myArray);
}