Reputation: 13
I'm a newbie here so please be with. I'm pretty sure that my code and syntax is correct.
This is my json file
{"data":
[
{"label":"Signed-in Client","value":2
}
]
}
This is my php code
<?php
$conn=mysqli_connect("localhost", "root","","something");
$res1 = mysqli_query($conn, "SELECT * FROM tbl_pet_owner ORDER BY pet_owner_id");
$max1 = mysqli_num_rows($res1);
$jsonString = file_get_contents('data.json');
$data1 = json_decode($jsonString, true);
foreach ($data1['data'] as $key )
{
if ($key[0]['label'] == "Signed-in Client")
{
$data1['value'] = $max1;
}
}
$newJsonString = json_encode($data1);
file_put_contents('data.json', $newJsonString);
?>
but when I refresh, it doesn't update with the max count of my query. I hope you'd help me. This is for my thesis
Upvotes: 1
Views: 450
Reputation: 13097
It seems to me that the problem is connected with the way how you traverse the data.
For example in foreach ($data1['data'] as $key )
, $key
is already an associative array (e.g., array("label" => "Signed-in Client", "value" => 2)
), so instead of $key[0]['label']
, one should use just $key['label']
.
Also, when you want to modify the 'value'
, one has to access the same associative array, not the original variable $data1
.
One way to achieve this would be as shown below. In that example the array $data1['data']
is traversed using references (&$key
). Note that one should then unset this variable after the foreach
block to break its association with the last element of the array being traversed.
<?php
$max1 = 100;//just an example
$jsonString = file_get_contents('data.json');
$data1 = json_decode($jsonString, true);
foreach ($data1['data'] as &$key )
{
print_r($key);
if($key['label'] == "Signed-in Client")
{
$key['value'] = $max1;
}
}
unset($key);
print_r($data1);
/* gives:
Array
(
[data] => Array
(
[0] => Array
(
[label] => Signed-in Client
[value] => 100
)
)
)
*/
//$newJsonString = json_encode($data1);
//file_put_contents('data.json', $newJsonString);
?>
Upvotes: 2