Highchart automatically add quotes to the variable - php

I use hightchartPHP to display chart. But being a bug, hope people take the time to read and help me.
$chart->series[] = array(
'name' => 'Sales',
'data' => array(1,2,3,4,5,6));
Code run.
[1,2,3,4,5,6]
But, i get data mysql
$chart->series[] = array(
'name' => 'Sales',
'data' => array($sales->monthly_sales()));
then automatic highchart add quote . Code not run.
["1,2,3,4,5,6"].
I tried by add json_encode. But code not run.
["\"1,2,3,4,5,6\""]

Try using JSON.parse before you send data (string) into a series data.
series : [{
data: JSON.parse(data)
}]
Because you get string with php not a javascript array of numbers! another easy and not good approach is to remove quotes from your php string $sales->monthly_sales() with something like this:
str_replace('"', "", $string);

Related

How to update JSON field in database with non-primitive value?

The json column in the database has a data like this:
{"data": {"total":15,"time":25}}
This is the data I want to update within it:
{"total":22,"time":5}
But when updating the data via Laravel like this:
$json_data = json_encode(['total' => 22, ...]);
$table->where->update(['column->data' => $json_data])
the result is as follows:
{"data": "{\"total\":22,\"time\":5}"}
When I pass the array without json_encodeing it, it raises an error instead.
How can I assign a non-primitive value directly to a property in a JSON field?
I think the only solution is as follows:
$data = ['total' => 22, 'time' => 5];
$table->where->update([
'column->data->total' => $data['total'] ,
'column->data->time' => $data['time']
])
I searched to batch update the contents of a json key without double quotes but couldn't find it.
Either the content will be pulled completely and then edited and sent again. Or individual updates will be made as above. Please let me know if you find a better solution.
seems it got double json encoded, first you json_encode'ed it manually, then the $table->where->update-function json_encode'ed it again. try replacing
$json_data = json_encode(['total' => 22, ...]);
with just
$json_data = ['total' => 22, ...];

Laravel - pluck with specified keys

I have a line of code similar to the following:
Sport::pluck('id', 'name)
I am dealing with frontend JavaScript that expects a list in this format:
var list = [
{ text: 'Football', value: 1 },
{ text: 'Basketball', value: 2 },
{ text: 'Volleyball', value: 3 }
...
]
I am trying to figure out how I can somehow transform the id and name values that I pluck from my model to a format similar to the Javascript list.
If that's unclear, I am looking to end up with an associative array that contains two keys: text and value, where text represents the name field on my model, and where value represents the id of the model - I hope this makes sense.
How would I approach this?
I initially tried something like this (without checking the documentation)
Sport::pluck(["id" => "value", "name" => "text]);
But that isn't how you do it, which is quite clear now. I've also tried some map-related snippet, which I cannot seem to Ctrl-z to.
Any suggestions?
Another method is to use map->only():
Sport::all()->map->only('id', 'name');
The purpose of pluck is not what you intend to do,
Please have a look at below examples,
Sport::selectRaw("id as value, name as text")->pluck("text","value");
// ['1' => 'Football', '2'=>'BasketBall','3'=>'Volleyball',...]
Syntax
$plucked = $collection->pluck('name', 'product_id');
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
Please see the documentation.
Your output is possible using simple code.
Sport::selectRaw('id as value, name as text')->get();
You could use map.(https://laravel.com/docs/5.8/collections#method-map)
$mapped = Sport::all()->map(function($item, $index) {
return [
"id" => $item["id"],
"name" => $item["text"]
];
});
This is the easiest way. Actually Laravel offers a better way for it. You can use api resources to transform your data from eloquent for the frontend:
https://laravel.com/docs/5.8/eloquent-resources
Try with toArray function:
Sport::pluck('id', 'name)->toArray();
Then you can return your result with json_encode php function;

How to edit data sql for Json output

I want to add this symbol [ ] to the column "Post_images"
with basis data sql server
Like this,
“post_images” : “ht tp://img*sample*com/gambar1*jpg”, “ht tp://img*sample*com/gambar2*jpg”
to
“post_images” : [“ht tp://img*sample*com/gambar1*jpg”, “ht tp://img*sample*com/gambar2*jpg”]
In json the [] indicates a set of items.
Assuming you have an array with both strings inside then calling json_encode(array) should add the [ ].
See also this tutorial for more detais.
http://www.tutorialspoint.com/json/json_php_example.htm
Please do not write json on your own. Use the php functions instead.
You have to place array for post_images
it mean if you have $data which you json_encodeing you should add your post images as sub array not string. Example
$data = array(
'param1' => "data ...",
'post_images' => array(
“ht tp://img*sample*com/gambar1*jpg”,
“ht tp://img*sample*com/gambar1*jpg”
);
);
echo json_encode($data); // will output what you where looking for
Do the the following:
'["ht tp://imgsamplecom/gambar1*jpg", "ht tp://imgsamplecom/gambar2*jpg"]'
Example:
http://sqlfiddle.com/#!9/971279/1

add value to JSON of title

I search a lot in stack and google try to find the answer which seems to be easy but I'm still stuck with it
I write a code to encode json with values I wanted from . and I would like to add a key / value to the JSON
the JSON is as following structure
{
- files: [
{
title: "works",
- tracks: [
{
title: "File",
format: "mp3"
}
]
},
-{
title: "season1",
tracks: [
{
title: "Button-1",
format: "wav"
},
-{
title: "Beep-9",
format: "wav"
}
]
}
]
}
I want to add to that a key and its value at the beginning to the json as properties under the title files , I mean that can be read by code as
json[files][new_key]
I tried to set that value like this
$json['new_key'] = "new_value";
but this causes adding numbers to the arrays in json , I don't why they numbered
this numbers affect my reading way of the json as JSONModel in my iOS app
so , I hope you can help me
thanks in advance
Assuming that the new value you want to add varies by file, you would need to loop through $json[files] and insert them per key/value pair.
<?php
for($i=0; $i<count($json); $i++)
$json[files][$i]["new_key"] = "value";
?>
I'm still not sure what you have exactly, but it seems you are trying to manipulate the json string.
If done correctly, that is probably the most efficient solution, but what you could also do is:
use json_decode to generate an array from your json string;
locate the correct section / sub-array where you want to add your data;
use array_unshift to prepend your new key - value pair;
use json_encode to generate a json string from your complete array.
The reason you're getting numbers appearing is because you're adding a key to an array (which functions more or less as a list in JS). So before you basically have the object "files" as a list of objects zero-indexed like any other JS array. When you add the key, JS simply adds your key to the end of your present keys (in your case 0 and 1).
It seems like you have a list of multimedia objects where each has a title and a list of tracks. The most straightforward way to solve your issue would be as follows:
$fileItem['title'] = 'works';
$fileItem['tracks'] = array(
array(
'title' => 'File',
'format' => 'mp3'
)
);
$json['files'][] = $fileItem;
$fileItem['title'] = 'season1';
$fileItem['tracks'] = array(
array(
'title' => 'Button-1',
'format' => 'wav'
),
array(
'title' => 'Beep-9',
'format' => 'wav'
)
);
$json['files'][] = $fileItem;
Then you JSON encode it and return it as you normally would. You can put the above in a loop as well. I lack enough context to recommend exactly how.

Updating Flot PHP, AJAX, JSON

I am having some trouble updating a Flot bar chart from an Ajax request to a PHP script that returns JSON data.
The PHP script is:
$vars = array(
'result' => "success",
'msg' => AJAX_SUCCESS,
'series' => "Group One,80,Group Two,10"
);
echo json_encode($vars);
This is returned to a variable 'series'
var data = [series.series];
This outputs to the console:
Group One,80,Group Two,10
I also have a commented out variable which is:
//var datatwo = [ ["Group One", 80], ["Group Two", 10] ];
This also outputs to the console
Group One,80,Group Two,10
The actual javascript to create the graph is
$.plot("#group-month-graph", [data], options);
The options are assigned at another location of the script.
Im trying to figure out what Im doing wrong as when I alert the returned data or output it to the console the values are identical, however the returned data will not draw the graph whereas if I use the commented out value it does.
Hope that makes sense. I have cut down the full script as I dont think that the issue lies anywhere else.
You are returning a String while the plugin is expecting an Array. You should return [["Group One",80],["Group Two",10]]
Change your php series structure to:
$vars = array(
'result' => "success",
'msg' => AJAX_SUCCESS,
'series' => array(array("Group One",80),array("Group Two",10))
);
Also, you should be getting the series array using data and not [data]
$.plot("#group-month-graph", data, options);

Categories