how to make index at foreach and make it as json? - php

I want to save my data from foreach as "name data": value to variable ChartVal, but I don't how to do it I'm still learning.
<?php
$nim = $this->uri->segment(3);
$chart = $this->modelpenilaian->getchart($nim);
foreach ($chart as $ca) {
$a[i] = "$ca->name": $ca->nilai;
} //I know this is wrong, I just don't know the right one
?>
<script>
var chartVals = <?php echo json_encode($a[i])?>;
//I want to save to variable chartVals
$(function(){
$('#chart').radarChart({
size: [500, 400],
step: 1,
title: " ",
values: {
//"chartVals": chartVals
//then send it to jquery value
chartVals
},
showAxisLabels: true
});
});

You most likely need to set the key of $a array to the name you want ($ca->name in your case)....
$a=array();
foreach ($chart as $ca) {
$a[$ca->name] = $ca->nilai;
}
and then
echo json_encode($a);
When adding the data to the chart, you need to use
values: chartVals,

Is this what you're looking for?
foreach ($chart as $ca) {
$a[$ca->name] = $ca->nilai;
}
That gives you an array of key:value pairs. To turn it into JSON you would:
$myJSON = json_encode($a);

Related

Print strings in PHP where item orders are collected from JSON

I have a JSON item list in the database that holds the the serial number of different items to be printed according to the order of their serial number. The JSON structure is like this:
{
"item_list": [
{
"item_sl": "1",
"item_print": "flowers"
},
{
"item_sl": "2",
"item_print": "cars"
}
]
}
After retrieving it from the database, I decoded the items in $items_array and then tried to create variables like $item1, $item2 ... which I wanted to assign to the item_print values from the JSON. The same print values have been already defined earlier ($cars, $flowers). Lastly, I wanted to print all of them. The code is:
$cars = 'Tesla is my favorite.';
$flowers = 'I love all flowers.';
$items_array = json_decode($items_data, true);
foreach ($items_array['item_list'] as $item_list) {
foreach ($item_list['item_sl'] as $key => $n) {
${'item'.$n} = $item_list['item_print'][$key];
}
}
$all_print = $item1.' '.$item2;
echo $all_print;
But $all_print is returning null, which tells me my approach is not correct. What am I missing here? What would be a better approach for printing the $cars and $flowers variables according to the serial numbers from the JSON?
First of all, there is no need to use multiple loops when you can achieve the same with a single loop.
Also, there is no need to create variables dynamically and assign values when you can directly decode the JSON and access each value without creating variables and assigning them dynamically.
This should work:
<?php
$items_data = '{
"item_list": [
{
"item_sl": "1",
"item_print": "flowers"
},
{
"item_sl": "2",
"item_print": "cars"
}
]
}';
$items_array = json_decode($items_data, true);
foreach ($items_array['item_list'] as $item) {
${'item' . $item['item_sl']} = $item['item_print'];
}
$all_print = $item1.' '.$item2;
echo $all_print;
?>
Output:
flowers cars
For Your Code above, i don't Really Understand it well, but i think this may help if you are trying to loop items from a json encoded data.
$items_array = json_decode($items_data, true);
foreach ($items_array->item_list as $item_list) {
echo $item_list->item_sl;
echo $item_list->item_print;
}
EDITED
Two Methods to achieve this
First:
$items_array = json_decode($items_data, true);
foreach ($items_array["item_list"] as $item_list) {
echo $item_list["item_sl"];
echo $item_list["item_print"].'<br>';
}
Second:
$items_array = json_decode($items_data);
foreach ($items_array->item_list as $item_list) {
echo $item_list->item_sl;
echo $item_list->item_print;
}
ADDITIONALLY:
if you want to display output based on the user item_print, then you can do this;
$items_array = json_decode($items_data, true);
foreach ($items_array["item_list"] as $item_list) {
if ($item_list["item_print"] == 'cars') {
echo $cars."<br>";
}elseif($item_list["item_print"] == "flowers"){
echo $flowers;
}
}

JSON Get the name of dynamically changing key with PHP

I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.

how to read from json array in codeingiter

Im trying to decode json and get value from the json code.
[{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":1,
"menu_category_id":1,
"status":0
} ,
{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":2,
"menu_category_id":1,
"status":0
}]
i need to read from this json and create an array with add_food_item_a and status.
currently I'm using like this
public function readJson()
{
$json_obj = json_decode('');
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]) && !empty($GLOBALS["HTTP_RAW_POST_DATA"])) {
$json_text = $this->cleanMe($GLOBALS["HTTP_RAW_POST_DATA"]);
// now insert into user table
$json_obj = json_decode($json_text);
}
return $json_obj;
}
and I call this function like
$add_food_item_a = isset($json_obj->add_food_item_a) ? $json_obj->add_food_item_a : '';
but can't read from this array of json code
Are you trying to fetch the value of 'add_food_item_a' and 'status'
<?php
$json='[{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":1,
"menu_category_id":1,
"status":0
} ,
{
"restaurant_id":1,
"menu_template_id":2,
"add_food_item_a":2,
"menu_category_id":1,
"status":0
}]';
echo "<pre>";
$array = json_decode($json,1);
print_r($array);
foreach($array as $value)
{
echo "\n".$value['add_food_item_a'];
echo "\n".$value['status'];
}

JSON manipulation in PHP?

I need to edit some data in a JSON file, and I'm looking to do so in PHP. My JSON file looks like this:
[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]
What I've done so far is $data = json_decode(file_get_contents(foo.json)) but I have no idea how to navigate this array. If for example I want to find the data from the first field of the second object, what's the PHP syntax to do so? Also, are there other ways I should know about for parsing JSON data into a PHP friendly format?
This JSON contains 2 arrays with 2 objects each, you can access like this:
$arr = json_decode(file_get_contents(foo.json));
// first array
echo $arr[0]->field1;
echo $arr[0]->field2;
// second array
echo $arr[1]->field1;
echo $arr[1]->field2;
if you convert this to an array and avoid objects you can then access like this:
$arr = json_decode(file_get_contents(foo.json), true);
// first array
echo $arr[0]['field1'];
echo $arr[0]['field2'];
// second array
echo $arr[1]['field1'];
echo $arr[1]['field2'];
$data = json_decode(file_get_contents(foo.json));
foreach($data as $k => &$obj) {
$obj->field1 = 'new-data1-1';
$obj->field2 = 'new-data1-2';
}
Please use this code to navigate through your json format. This code is dynamic and can navigate for any number of objects you have in your result.
<?php
$json ='[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]';
if($encoded=json_decode($json,true))
{
echo 'encoded';
// loop through the json values
foreach($encoded as $key=>$value)
{
echo'<br>object index: '.$key.'<br>';
foreach($value as $bKey=>$bValue)
{
echo '<br> '.$bValue.' = '.$bValue;
}
}
// get a perticular item
echo '<br>object[0][field1]: '.$encoded[0]['field1'];
}
else
{
echo'error on syntax';
}
?>
Which will have following output
encoded
object index: 0
data1-1 = data1-1
data1-2 = data1-2
object index: 1
data2-1 = data2-1
data2-2 = data2-2
object[0][field1]: data1-1

Send json data into a php variable to be used in javascript

I'm quite new to php and don't actually know if this is possible
Im currently outputting JSON code with php using the following code
echo json_encode($output, JSON_NUMERIC_CHECK);
But what I want to do is have the above data inside a variable.
I tried
$JSONDATAX = json_encode($output, JSON_NUMERIC_CHECK);
But it doesn't seem to like it when I call $JSONDATAX.
The original echo way works completely fine.
edit ........
$lrs = CDB::ExecuteQuery($sql);
if($lrs) {
$jsonData = convert($lrs);
}
function convert($lrs) {
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['POS'];
$x = $vals['CODE'];
$y = $vals['COUNT'];
$intermediate[$key][] = array('x' => $x, 'y' => $y);
}
$output = array();
foreach($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
$data1 = json_encode($output, JSON_NUMERIC_CHECK);
}
?>
<script>
var negative_test_data = <?php echo $data1; ?>;
var chart;
nv.addGraph(function() {
chart = nv.models.multiBarChart()
.color(d3.scale.category10().range())
.rotateLabels(0) //Angle to rotate x-axis labels.
.transitionDuration(300)
.showControls(true) //Allow user to switch between 'Grouped' and 'Stacked' mode.
.groupSpacing(0.24) //Distance between each group of bars.
;
As you can see, I am using php just after var negative_test_data , but it doesn't produce anything.
In your edited example, $data is a local variable inside the convert function, so it cannot be accessed outside that function. the result of json_encode should be returned:
$data1 = json_encode($output, JSON_NUMERIC_CHECK);
should be
return json_encode($output, JSON_NUMERIC_CHECK);
Then, the result of the convert function can be echoed:
var negative_test_data = <?php echo $data1; ?>;
should be
var negative_test_data = <?php echo convert($lrs); ?>;
(There should probably be a an additional if around that whole part, depending on what you want to happen when $lrs does not evaluate to true)
This should be all you really need:
$phpvar = json_encode($output);
echo "<script>var negative_test_data = {$phpvar};</script>";

Categories