-1

My json data is like this :

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

Note :

2 = star, 1 = user, 3 = star, 3 = user

If I have variables like this :

$user = 3;
$star = 4;

I want check variable $user exist in $json_data or not

If exist, it will update to be :

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

So, if $user exist in $json_data, it will update $star

I try like this :

<?php
    $user = 3;
    $star = 4;
    $json_data = '{"2": "1", "3": "3"}';
    $array_data = json_decode($json_data, true);
    if(in_array($user, $array_data))
    {
        // update here
    }
?>

I'm still confused, how to update it

Is there anyone who can help me?

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
moses toh
  • 12,344
  • 71
  • 243
  • 443

2 Answers2

2

You should use array_search() to check if the $user exists, and in case it does, it will return the array index.

$key = array_search($user, $array_data); // Returns 3 i.e array key where $user exists

if ($key !== false) {
    $array_data[$star] = $array_data[$key]; // If key found, set value to $array_data[4]
    unset($array_data[$key]); // Remove the previous data $array_data[3]
}

echo json_encode($array_data);

Output:

{"2":"1","4":"3"}
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
0

I think this code help you to resolve your Query

PHP Code

<?php
$result = array();
$json_data = '{"2": "1", "3": "3"}';
$user = 3;
$star = 4;
$dataArray = json_decode($json_data, true);
foreach($dataArray as $key=>$val) {
    if($val == $user) {
        $result[$star] = $val ;
    } else {
        $result[$key] = $val ;
    }
}
echo "<pre>";
print_r (json_encode($result));
?>
Aman Kumar
  • 4,533
  • 3
  • 18
  • 40