moses toh
moses toh

Reputation: 13192

How can I increment value of json data if it meets certain conditions?

My json data is like this :

$json_data = '{"1": "1", "2": "1"}';

Note :

1 = star

1 = the number of users who give star 1

2 = star

1 = the number of users who give star 2

If I have variables like this :

$star = 1;

I want check variable $star exist in key of $json_data or not

If exist, it will update to be :

$json_data = '{"1": "2", "2": "1"}';

So, if $star exist in key of $json_data, it will increment the value

I try like this :

<?php 
    $star = 1;
    $json_data = '{"1": "1", "2": "1"}';
    $array_data = json_decode($json_data, true);
    if(array_key_exists($star, $array_data)) {
        $value = $array_data[$star];
        if ($value !== false) {
            // update here
        }
                   
    }
?>

I'm still confused, how to update it

Is there anyone who can help me?

Upvotes: 0

Views: 3946

Answers (3)

Neil
Neil

Reputation: 14323

If you want everything to stay as strings inside of your JSON data I would use this code. I cast the variable first as an int then add 1 to it. Then I cast it as a string.

<?php 

$star = 1;
$json_data = '{"1": "1", "2": "1"}';
$array_data = json_decode($json_data, true);
if(array_key_exists($star, $array_data)) {
    $value = $array_data[$star];
    if ($value !== false) {
        $array_data[$star] = (string)((int)$value + 1);
    }

}

echo json_encode($array_data);

?>

Upvotes: 1

hendr1x
hendr1x

Reputation: 1501

$star = 1;
$json_data = '{"1": "1", "2": "1"}';
$array_data = json_decode($json_data, true);
if(array_key_exists($star, $array_data)) {
    if (isset($array_data[$star]) AND $array_data[$star] !== false) {
        $array_data[$star] = 'change';
    }

}
$json_data = json_encode($array_data);

You can also learn about passing variables as references but thats not needed here

Upvotes: 0

Atmahadli
Atmahadli

Reputation: 687

you can use isset()

if(isset($array_data[$star])) {
    $array_data[$star]++;
}else{
    $array_data[$star]=1;
}

Upvotes: 0

Related Questions