Yii2 How to pass php array data into highcharts - javascript

I am using Yii2 extension miloschuman/yii2-highcharts for charts and get confused passing php array into hightcharts.
My Array Values
Array
(
[Power Electronics] => 14.00
[Introduction to Programming] => 3.92
[Data base Management System] => 3.28
[Object Oriented Analysis and Design] => 1.96
)
Now simply what I want to add this data to my highcharts I am passing above array like my below code.
FROM MY HIGHCHARTS CODE
'series' => [
[
"name" => "Exam Results",
"data" => $course_data,
'dataLabels' => [
'enabled' => true,
'rotation' => -90,
'color' => '#FFFFFF',
'align' => 'right',
'format' => '{point.y:.1f}', // one decimal
'y' => 10, // 10 pixels down from the top
'style' => [],
'fontSize' => '13px',
'fontFamily' => 'Verdana, sans-serif',
],
],
],
I have already try many things but not get any success I wanted output like this charts.

Have you tried to call json_encode function with mentioned array passed as an argument? Here is the code:
<?php
$data = [
['Power Electronics', 14.00],
['Introduction to Programming', 3.92],
['Data base Management System', 3.28],
['Object Oriented Analysis and Design', 1.96],
];
echo json_encode($data);
[EDIT]
You can also try to use SeriesDataHelper feature. There is information about using it in the documentation, here is the link: https://github.com/miloschuman/yii2-highcharts/blob/master/doc/examples/series-data-helper.md#using-numerically-indexed-data
Here is example code:
use miloschuman\highcharts\SeriesDataHelper;
$data = $data = [
['Power Electronics', 14.00],
['Introduction to Programming', 3.92],
['Data base Management System', 3.28],
['Object Oriented Analysis and Design', 1.96],
]
'series' => [
[
"name" => "Exam Results",
"data" => new SeriesDataHelper($course_data, ['0:name', '1:y']),
'dataLabels' => [
'enabled' => true,
'rotation' => -90,
'color' => '#FFFFFF',
'align' => 'right',
'format' => '{point.y:.1f}', // one decimal
'y' => 10, // 10 pixels down from the top
'style' => [],
'fontSize' => '13px',
'fontFamily' => 'Verdana, sans-serif',
],
],
],

According to docs your array has invalid format. It should look like his:
$data = [
['Power Electronics', 14.00],
['Introduction to Programming', 3.92],
['Data base Management System', 3.28],
['Object Oriented Analysis and Design', 1.96],
];
You can fix this with simple foreach:
$newData = [];
foreach ($data as $key => $value) {
$newData[] = [$key, $value];
}

Related

Failed prop type: Invalid prop `rows` of type `object` supplied to `ForwardRef(DataGrid)`, expected `array`

Good day! I was wondering why I didnt display data on my grid table eventhough I can see or received data from my api response, I just wondering whats wrong on my code. here is my current code and please see my return data below, thanks
const UserModule = () => {
const logHeader = [
{ field: 'id', headerAlign: 'left', headerName: 'ID', hide: true, width: 50 },
{ field: 'firstname', headerAlign: 'left', headerName: 'First Name', width: 130 },
{ field: 'lastname', headerAlign: 'left', headerName: 'Last Name', sortable: true, width: 110 },
{ field: 'status', headerAlign: 'left', headerName: 'Status', width: 80 },
]
const [transactionLogData, setTransactionLogData] = useState([]);
useEffect(() => {
WorkflowApi.getTransactionLogForRevenueOfficer().then(logs => {
const newLogs = Object.fromEntries(Object.entries(logs).map( ([k,v]) => {
return [k, {
...v,
id: v._id
}] // I think the problem is here
}))
console.log("newLogs: ", newLogs)
setTransactionLogData(newLogs)
})
})
....
return (
<Grid item xs={12}>
<Box ref={componentRef}>
<RecordTable
columns={logHeader}
rows={transactionLogData}>
</RecordTable>
</Box>
</Grid>
)
}
//RecordTable.js
const RecordTable = (props) => {
const { columns, rows } = props
useEffect(async () => {
}, [rows])
//This type of array did my RecordTable component expects
// const sampleRows = [
// {
// "_id": 458,
// "LastUpdateDate": "2022-02-10",
// "status": "Approved",
// "firstname": "Yuno",
// "lastname": "Santiago",
// "id": 458
// }
// ]
return(
<DataGrid
....
columns={columns}
rows={rows}
....
/>
)
}
response i received from my api
{
"_id": 458,
"LastUpdateDate": "2022-02-10",
"status": "Approved",
"firstname": "Yuno",
"lastname": "Santiago",
"id": 458
}
this is the error i get
Warning: Failed prop type: Invalid prop rows of type object supplied to ForwardRef(DataGrid), expected array.`
Update after i remove the Object.fromEntries
const newLogs = Object.entries(logs).map( ([k,v]) => {
return [k, {
...v,
id: v._id
}] // I think the problem is here
})
i received this error
Uncaught Error: MUI: The data grid component requires all rows to have a unique id property.
check your rows props, it highly possible is empty object at first render.
To do so, you just console.log({rows}) and see the value printed in browser
I believe the problem is in the Object.fromEntries, the result of this method is always an object, not an array. Try to remove the Object.fromEntries, and leave only the Object.entries
For me, the problem is that I put the column content in another file.
I just put it in the app component and it solves the problem.
It creates an object if the column is in another file,
try to put your recordtable component in the same component(userModule I guess)

Get uniq values from an array of object created using lodash

I am new to the react, Here I am trying to get the unique elements from the newly created array of object.
const data = _.uniq(
orderData?.Sessions.map(session => ({
label: `${session.Activity.Name}`,
value: `${session.Activity.Name}`
}))
);
I have tried this but, still, it returns me the array of the object which has the unique elements using any of the two keys.
an object should not be duplicated.
can anyone help me with this?
It should be _.uniqBy(), refer uniqBy
const data = _.uniqBy(
orderData ? .Sessions.map(session => ({
label: `${session.Activity.Name}`,
value: `${session.Activity.Name}`
})), 'label' or 'value'
);
It should be either by label or by value
Example
document.querySelector("body").onload = function() {
// By 'label'
console.log("By label");
console.log(
_.uniqBy(
[
{'label' : 'name', 'value' : 'Test Name 1'},
{'label' : 'name', 'value' : 'Test Name 2'},
{'label' : 'company', 'value' : 'Test Company 1'}
], 'label'
)
)
// By 'vlaue'
console.log("By value");
console.log(
_.uniqBy(
[
{'label' : 'name', 'value' : 'SO User'},
{'label' : 'name', 'value' : 'SO User'},
{'label' : 'company', 'value' : 'Test Company 1'}
], 'value'
)
)
}
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.10/lodash.min.js"></script>
You have to use _.uniqBy(data, 'id');//id that is key you have to remove duplicate value from array
Your Scenario will be used like this
if removed by a label then
const data = _.uniqBy(
orderData ? .Sessions.map(session => ({
label: `${session.Activity.Name}`,
value: `${session.Activity.Name}`
})),'label'
);
if removed by a value then
const data = _.uniqBy(
orderData ? .Sessions.map(session => ({
label: `${session.Activity.Name}`,
value: `${session.Activity.Name}`
})),'value'
);
If you get more details then Link

how to build this json in php

im using php to send a push but my json object isent getting the way i want...
i need my json to be like this :
{
"to": ["xxx"],
"data": {
"title": "dw",
"body": "dw",
"actions": [
{ "icon": "emailGuests", "title": "Candidatar-me", "callback": "app.emailGuests", "foreground": true},
]
}
}
but im getting this instead :
{
"to": "xxx",
"data": {
"title": "dw",
"body": "dw",
"actions": {
"icon": "send.ico",
"title": "EMAIL GUESTS",
"callback": "app.callbackName",
"foreground": true
}
}
}
i am building my json like this :
$fields = array ( 'to' => $row1['fcm_registered_id'] ,
'priority' => "high",
'data' => array("title" =>$titlepost,
"body"=> $msg,
"actions" => array('icon' => 'send.ico',
'title' => 'EMAIL GUESTS',
'callback' => 'app.callbackName',
'foreground' => true
)
),
);
Remember that json_encodeconverts non-numeric indexed arrays to objects. There is why you gets objects instead of array of objects. It's enough to wrap this array by another array. Here is fixed code:
$fields = array (
'to' => array( $row1['fcm_registered_id'] ),
'data' => array(
"title" =>$titlepost,
"body"=> $msg,
"actions" => array(
array(
'icon' => 'send.ico',
'title' => 'EMAIL GUESTS',
'callback' => 'app.callbackName',
'foreground' => true
)
)
)
);
And here is working example: http://phpio.net/s/1n0e
Little note: try to use new array syntax: [] than old array()

How to display data in US Heat Map - Javascript - Laravel 5

I want to display data in a JS Heat map like this one:
This is the 2 diffrent types of data I'am receiving:
Im getting the data like this:
public function index() {
$regions = DB::table('locations')
->select('regionCode', DB::raw('count(id) as total'))
->groupBy('regionCode')
->get();
$newRegions = [];
foreach( $regions as $region ){
$newRegions[$region->regionCode] = $region->total;
}
return view('admin.dashboard-v2', compact('newRegions'));
}
And this is how I'm SUPPOSED to display it:
var map = AmCharts.makeChart( "chartdiv", {
type: "map",
"theme": "light",
colorSteps: 10,
dataProvider: {
map: "usaLow",
areas: [ {
id: "US-AL",
value: 4447100
}, {
id: "US-AK",
value: 626932
}, {
id: "US-AZ",
value: 5130632
}, {
id: "US-AR",
value: 2673400
}, {
id: "US-CA",
value: 33871648
},.... and so on
Im having trouble displaying it like above: How would I display the data im getting from the array into the 'areas' section in the ChartJS script?
I tried this, but it dosen't work:
areas: [ {
id: "US-{!! json_encode(array_keys($newRegions)) !!}",
value: {!! json_encode(array_values($newRegions)) !!}
} ]
is is a very common problem, transforming data structures to specific implementations.
the phpleague has many cool packages to help you with this.
one of my favorites is
http://fractal.thephpleague.com/
However, I want to show you in plain PHP how to transform an array into the desired structure.
1) get the array of data that you need to transform (the data that you showed in the previous image)
array:15[
0 => regioncode:"AL"
total: 16]
]...
2) transform the array using the array_map function
//http://php.net/manual/en/function.array-map.php
$transformedarray = array_map(function ($loopdata) {
return [
"id" => "US-".$loopdata['regionCode'],
"value" => $loopdata['value']
];
}, $regions->toArray());
3) var_dump($transformedarray) o return this array with laravel responde to check the desired structure match the one you require.
4) pass this variable (array) to the view using this method
return view('admin.dashboard-v2')->with(['newarray' => $transformedarray]);
5) if you are using BLADE try to user control structures to loop over your data
https://laravel.com/docs/5.0/templates
insert this code sniplet where you need the data to populate in the view
areas: [
#foreach ($newarray as $newarr)
{
id:{{ $newarr->id }},
value:{{ $newarr->value }}
},
#endforeach
]
Hope this helps
This is how I did:
$heatMap = DB::table('locations')
->select('regionCode', DB::raw('count(id) as total'))
->groupBy('regionCode')
->get();
$newHeatMap = [];
foreach( $heatMap as $regionH ){
$newHeatMap[] = [ 'id' => 'US-' . $regionH->regionCode, 'value' => $regionH->total ];
}
return view('admin.dashboard-v2', compact('newHeatMap'));
Then In my Chart JS
dataProvider: {
map: "usaLow",
areas: {!! json_encode(array_values($newHeatMap)) !!}
},

update yiiwheels highchart via javascript

I'm using highchart widget from yiiwheels (extension for Yii framework):
<?php $this->widget('yiiwheels.widgets.highcharts.WhHighCharts',array(
'pluginOptions' => array(
'title' => array('text' => 'Fruit Consumption'),
'xAxis' => array('categories' => array('Apples', 'Bananas', 'Oranges')),
'yAxis' => array('title' => array('text' => 'Fruit eaten')),
'series' => array(
array('name' => 'Jane', 'data' => array(1, 0, 4)),
array('name' => 'John', 'data' => array(5, 7, 3))
)
)
));?>
echo TbHtml::button('Refresh Chart', array('id'=>'refreshButton')); ?>
<script type="text/javascript">
$('#refreshButton').click(function() {
var chart = $('#container').highcharts(); // THIS IS NOT WORKING, HELP!!!
chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5] ); // sample data
});
</script>
This works well if I use native highcharts.js from highcharts.com
But like I said, I use yiiwheels's highcharts widget.
How can I fix this, how to refer my chart from javascript/jquery?
Thanks

Categories