ChartJS Arrays Acting as One Item - php

I'm trying to import readings from mySQL database, and place them on a ChartJS.
$query = mysqli_query($conn, "SELECT * FROM readings
ORDER BY readings_id DESC LIMIT 2");
$distance = array();
$timestamp = array();
while($row = mysqli_fetch_array($query)) {
$distance[] = $row['river_height'];
$time[] = $row['time_stamp'];
}
This is the query I'm using and the method I'm doing to store readings in an array.
However, when I try to place these in a bar chart for example, the 2 readings will act as one.
I have the Javascript code as follows:
const time = <?php echo json_encode($time); ?>;
var canvasElement = document.getElementById("chart");
var config = {
type: 'bar',
data: {
labels: [time],
datasets: [{data:[10, 20]}],
}
}
I've tried quite a lot of things, but can't figure it out. I'm new to this, so it doesn't help. Any advice or help would be appreciated.

This is happening because your PHP is returning an array for the labels and then you put that array in another array. This tells chart.js that it has to be a multiline label as you can see.
To get the behaviour you want you need to remove the array brackets at the labels field like so:
const time = <?php echo json_encode($time); ?>;
var canvasElement = document.getElementById("chart");
var config = {
type: 'bar',
data: {
labels: time, // remove array brackets around time
datasets: [{data:[10, 20]}],
}
}

Assuming you want time_stamp as the X axis, and river_height as the Y axis, change to :
PHP :
while($row = mysqli_fetch_array($query)) {
$data[] = [
'x' => $row['time_stamp'],
'y' => $row['river_height']
];
}
JavaScript :
var config = {
type: 'bar',
data: {
datasets: [{
data: <?= json_encode($data) ?>
}]
}
};

Related

Array to nested Json

I try to convert some data into a json. The data looks like this:
$one = ["ID","Name","Address1","Address2"];
$two = ["KJS0001","Mike","Cairo","Egypt"];
$three = ["KHO0001","Jhon","Paris","France"];
The Output I want to get is:
{
"KJS0001":{
"Name":"Mike",
"Address":["Cairo","Egypt"]
},
"KHO0001":{
"Name":"Jhon",
"Address":["Paris","France"]
}
}
Since the amount of nested attributes varies and its indexed with id also how to make Address (contain data from address1 and address2 array). Can anyone help me?
This is one possible solution, By creating new array and use json_encode
<?php
$data = array();
//$columns = ["ID","Name","Address1","Address2"];
$data[] = ["KJS0001","Mike","Cairo","Egypt"];
$data[] = ["KHO0001","Jhon","Paris","France"];
$result = array();
foreach($data as $value){
$result[] = [$value[0] => ["Name"=>$value[1],"Address"=>[$value[2],$value[3]] ] ];
}
echo json_encode($result);
?>
Column name, you mentioned in $one is not needed if columns are fixed.
Live demo : https://eval.in/621908
Output is :
[
{"KJS0001":{"Name":"Mike","Address":["Cairo","Egypt"]}},
{"KHO0001":{"Name":"Jhon","Address":["Paris","France"]}}
]

A Simple Random Generator

How can I create a generator where when a button is pressed it selects a random word that I've added to a list.
For example, "Apple", "Banana" and "Pear" are on my list and I want the end user to press a button and the code will fetch one of the fruits but completely randomly, how can I do this?
Regards,
John
First, you mention a list; this directly translates to an array.
Second, you have a finite number of options, presented in the array, and you want to pick one at random. This translates to picking an index (integer) at random. Since arrays start at 0 and you cannot choose an item passed the last index, you will then need to choose a random range between 0 and the length of the array.
If you simply want to get a random item from a list from pressing a button, you'll most certainly want to isolate this to the front-end, i.e. javascript:
var randomWords = [
'Apple',
'Banana',
'Pear'
];
function getRandomWordFromList(list) {
var index = getRandomInt(0,list.length);
return randomWords[index];
}
function getRandomInt(min,max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
document.getElementById('myButton').onclick = function() { // for example's sake...
document.getElementById('theOutput').innerHTML = getRandomWordFromList(randomWords);
};
(getRandomInt from Generating random whole numbers in JavaScript in a specific range?)
Also, if your array is fragmented (i.e. some indices are missing), you can use (safer, albeit more convoluted):
function arrayKeys(array) {
var i,keys = [];
for ( i in array ) {
if ( isInt(i) && array.hasOwnProperty(i) ) {
keys.push(i);
}
}
return keys;
}
function isInt(value) {
return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10));
}
function getRandomInt(min,max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomWordFromList(list) {
var keys = arrayKeys(list); // be sure to only get indices that exist
var key = getRandomInt(0,keys.length-1);
return list[keys[key]];
}
var randomWords = [
'Apple',
'Banana',
'Pear'
];
delete randomWords[1]; // remove 'Banana'
var theWord = getRandomWordFromList(randomWords);
If there is something server-side that influences the randomized list, you can populate the randomWords array via PHP as follows:
<?php
$randomWords = array(
'Apple',
'Banana',
'Pear'
);
?>
<script type="text/javascript">
var randomWords = [<?php echo "'".implode("','",$randomWords)."'"; ?>];
// don't forget your getRandomWord functions
</script>
Bonus: If the randomization must happen entirely server-side, i.e. php, here is a translation:
<?php
$randomWords = array(
'Apple',
'Banana',
'Pear'
);
echo $randomWords[array_rand($randomWords)]; // output somewhere
?>
A simple javascript closure to demonstrate.
var generateRandom = (function () {
var fruit;
return function () {
if (fruit === undefined) {
fruit = ["Apple", "Banana", "Pear"];
}
return fruit[Math.floor(Math.random() * fruit.length)];
}
}());
Here Math.random gives a number between 0 and 1. so I will be multiplying it with the array length to get a number between 0 and fruit.length. this would be the index of the item that we are going to pick.
Here's just a quick example of how to might do this. Actions (clicking in this case) are taken care of by JavaScript, so I highly recommend taking care of all of it there. The idea is that you don't need to have separate html or especially php worry about this when you could package it up in a JavaScript object. This code is far from perfect, but I think it's a good starting point for you. Notice that all you need to do to make this run is have this script included and simply type (in js) wordRandomizer.run(myElem); when myElem is a reference to an element that is in the dom (I just used the body in this example).
Demo here.
var wordRandomizer = { //the name of your "app"
run : function(targetElem) { //this is the function you will call to make it all happen
var markup = this.createMarkup();
targetElem.appendChild(markup);
},
createMarkup : function() {
var that = this;
var frag = document.createDocumentFragment();
this.elem = document.createElement('span');
var button = document.createElement('button');
button.innerText = 'Change Item';
button.addEventListener('click', function() {
that.changeItem();
});
frag.appendChild(this.elem);
frag.appendChild(button);
return frag;
},
changeItem : function() {
var rand = this.getRandInt(1, this.items.length) - 1; // -1 because arrays start at 0
this.elem.innerText = this.items[rand];
},
getRandInt : function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
items : [
'itemA',
'itemB',
'itemC',
'itemD'
]
};
wordRandomizer.run(document.body);
//here, you just pass in the element where your "app" will attach its output.
//If you want to get fancier, you could make more things optional, add more functionality, etc and pass in those options here.
Oh, and you should add some logic to make sure the item selected will not be the same item as before. There's several ways to do that easily, but I'll leave the fun to you :)
Using Javascript:
var fruit;
var rand = Math.random();
if (rand <= 0.33) {
fruit = 'Apple';
} else if (rand > 0.34 && rand <= 0.66) {
fruit = 'Banana';
} else if (rand > 0.67) {
fruit = 'Pear';
}
Math.random() will return a number between 0 and 1.

Saving Javascript Array to PHP

Hello i am quite new to javascipt so please explain things clearly. I am currently running a php page which includes:
upp.php
<script>
document.getElementById("data").value = localStorage.getItem('itemsArray');
</script>
this items array contains objects which is saved like this:
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {};
var num = document.getElementById("num").value;
newItem[num] = {
"methv": document.getElementById("methv").value
,'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
$.post('upp.php',{ items: JSON.stringify(oldItems) }, function(response) {
window.location.href = "upp.php";
the result of the page appears like this:
[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]
is there anyway i can save this information into PHP and split the data so I can manipulate it one at a time like a loop or something. For example:
1st time:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
Next:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
etc.
Thanks.
upp.php:
<?php
$array = json_decode($_POST['items'], True);
foreach ($array as $key=>$line) {
# $key is a number like 1173627548
# and $Line is an array with methv, q1, q2, q3, q4, and comm
}
?>
That will show you the array it got from the JSON. Now you can work with the data.

Order Array by Relevant Search Results

I know that there has to be a library for this somewhere, but what I am trying to do is pass in an array of strings, and a search string and have it order the array by how relevant it is to the search string.
I have been having a hard time figuring out what to google to figure this out, anyone point me in the right direction?
preferably in php, or another server side language
I don't really know what you mean by 'revelant'..
But, if you want to find the best string based on a search string, you can use the Levenshtein algorithm. It calculate a "distance" between two strings.
More infos here : http://php.net/manual/fr/function.levenshtein.php
This is kinda tricky and I cannot really explain in English, so I'll just have to show you a working code. If you have an questions, you can ask.
<!DOCTYPE html>
<head>
<title>Search Array</title>
<script>
//so let's set an array of values we will be searching
function searchArray(dis) {
var bigContent = new Array('Jesus loves you','Angle','God in Heaven','Bala','Overcomer','Be born again','Adesuwa','Heaven is real','James','Apple','John the baptist');//this is the array that serves as your database
var searchi = dis.value, result = Array();
searchi = searchi.toLowerCase();
//order the array alphabetically
bigContent = bigContent.sort();
var content;
if(searchi !='') {
//Define the arrays for initial pre-storage
var keys = new Array(), contentArray = new Array();
//Loop through the content array to search for all occurence of string
for(var i=0;i<bigContent.length;i++) {
content = bigContent[i].toLowerCase();
if(content.indexOf(searchi) > -1) {//found the search in this value
//get the position of the search string in content
var pos = content.indexOf(searchi);
//make position the key for your content array
if(contentArray[pos]) {//check if this position has already been assigned to a content
//if yes, append this content.
contentArray[pos] += '[]'+bigContent[i];
} else {//else, set the content
contentArray[pos] = bigContent[i];
//only save the position the first time you find it, to avoid duplication
keys[keys.length] = pos;
}
}
}
//sort the key so it can order the values in ascending order(relevance)
keys = keys.sort();
//loop thru the key
for(var i=0;i<keys.length;i++) {
var key = keys[i];//remember the value of "var key" is the key for contentArray value
if(contentArray[key]) {//just to be sure it's ther
var thisContent = contentArray[key];
//check if the content has more than 1 value
if(thisContent.indexOf('[]') < 0) {//if it doesn't
result[result.length] = contentArray[key];
} else {//if it does
//convert content into array
var thisContentAr = thisContent.split('[]');
//Loop thru the array
for(var j=0;j<thisContentAr.length;j++) {
result[result.length] = thisContentAr[j];
}
}
}
}
}
document.getElementById('ov').innerHTML = '';
for(var i = 0; i<result.length;i++) {
document.getElementById('ov').innerHTML += '<div>'+result[i]+'</div>';
}
}
</script>
</head>
<body>
<div><input type="text" onkeyup="searchArray(this);" autofocus="autofocus" /></div>
<div id="ov"></div>
</body>
</html>

Php javascript conflict with passing javascript to php

I have a slight problem. I have several arrays in php with different team names. Each array contains teams of a certain league. When I click an add button I get the option to add a new entry to the calendar. I want the drop down to have only the teams for that league. onclick of the add button I call a javascript function that knows what division was clicked. However in order to give the javascript the information for which teams to display I have to pass it one of the php arrays. The problem I am having is telling php which array to pass to javascript depending on which league javascript is on. I don't want to specify the array myself because there is an option to add a league and this would mean having to code in more code each time a league is added. The point of the site is being dynamic.
here is some code.
for ($i = 0;$i<$sizeof($leaguesarray);$i++){
$htmlimploded[$i] = implode($html[$i]);
}
here I have used emplode to make all of my php arrays readable into javascript.
for (var h = 0; h<size; h++){ // goes through every league
if(h == leaguenum){ // finds the league for the clicked add button
// this is the line that I have trouble with I can't think of
//anyway of telling it which array to use since it is serverside code.
var myarray = ["<? echo $htmlimploded[]?>"];
}
}
Javascript code above.
Imploding works but why not json_encode($array)? It's a simpler, built in way to turn php arrays into javascript objects or arrays. If you have something like:
$league1 = array('team1', 'team2');
$league2 = array('team3, 'team4') ;
Then make a multidimensional associative array of these:
$all_teams = array('league1'=>$league1, 'league2'=>$league2);
encode it into a Javascript object and print it into your JS:
$encoded = json_encode($all_teams);
print 'var teamObject = '.$encoded.';';
If you were to console.log(teamObject) you'd see something like this:
{"league1": ["team1", "team2"], "league2": ["team3", "team4"]}
Looks complicated, but now you can pull out the array you desire very easily. The league 1 array is teamObject.league1 and the league2 array is teamObject.league2, and so on.
i think you missed something in the following code:
var myarray = ["<? echo $htmlimploded[]?>"];
By right, it should be:
var myarray = ["<?php echo $htmlimploded[]?>"];
Assuming that PHP knows the names of the leagues and the teams and that JavaScript knows the league name that is clicked, You can wrap the arrays of the team names inside an object with the league as the name of the property.
<?php
$arr = array("League1" => array("Team 1", "Team 2"),
"League2" => array("Team 3", "Team 4")
);
?>
var obj = {};
<?php foreach ($arr as $k => $v): ?>
obj.<?php echo $k; ?> = ["<?php echo implode('","', $v); ?>"];
<?php endforeach; ?>
Then when a user selects a league, you can loop through the array of the property (which is the league name) of the object.
clickedLeague = "League1";
for (var i = 0; i < obj[clickedLeague].length; i++)
{
console.log(obj[clickedLeague][i]); // Logs the team name to console
}

Categories