I have an array;
$arr=array(1100,3150,4430,4430,5170,7450,7450,7450,8230);
I want to show them in graph. I want my Y-Axis as my elements of that array and X-Axis as sum up the numbers until that element. (x1,x1+x2,x1+x2+x3,...)
My graph will be;
Y-Axis : 1100,3150,4430,4430,5170,7450,7450,7450,8230
X-Axis : 1100,4250,8680,13110,18280,25730,33180,40630,48860
But I have no idea about how to do that. Is there anyone who can help me with it ? Thanks.
My entire code:
<?php
echo " ".'<br>'.'<br>';
$arr=array(1100,3150,4430,4430,5170,7450,7450,7450,8230);
$arrtotal=0;
for($i=0; $i<=8; $i++)
{
if ($arr[$i]<100) {
$arr[$i]=$arr[$i];
}
else
{
$arr[$i]=$arr[$i]/1000;
$arr[$i]=(string)$arr[$i];
}
}
function calculate($arr, $output){
switch($output){
case 'mean':
$count = count($arr)+1;
$sum = array_sum($arr);
$total = $sum / $count;
break;
case 'median':
rsort($arr);
$middle = (count($arr) / 2)+1;
$total = $arr[$middle-1];
break;
case 'mode':
$v = array_count_values($arr);
arsort($v);
foreach($v as $k => $v){$total = $k; break;}
break;
}
return $total;
}
function sd_square($x, $total) { return pow($x - $total,2); }
function sd($arr) {
return sqrt(array_sum(array_map("sd_square", $arr, array_fill(0,count($arr), (array_sum($arr) / count($arr)) ) ) ) / (count($arr)-1) );
}
echo ' '.'<br>';
echo "Values: ";
echo json_encode($arr).'<br>';
echo 'Mean: '.calculate($arr, 'mean').'<br>';
echo 'Median: '.calculate($arr, 'median').'<br>';
echo 'Mode: '.calculate($arr, 'mode').'<br>';
echo "Standart Derivation: ".sd($arr);
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function () {
var data = <?php echo json_encode($arr, JSON_NUMERIC_CHECK); ?>;
data = data.map(function (row, index) {
return {
x: index,
y: row
};
});
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Analysis"
},
axisY: {
title: "Variables"
},
data: [{
type: "line",
dataPoints: data
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 250px; width: 50%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
In this code my X-Axis is (0,1,2,3,4,5,6,7,8) and I don't want that.
I'm sorry if I couldn't explain well, English is not my native language.
The simplest way is just to loop over the values, adding the current array value to the previous output value to create the new output value. You can then convert that into an array of [x => y] values using array_combine:
$arr=array(1100,3150,4430,4430,5170,7450,7450,7450,8230);
$out = array($arr[0]);
for ($i = 1; $i < count($arr); $i++) {
$out[$i] = $out[$i-1] + $arr[$i];
}
$arr = array_combine($out, $arr);
print_r($arr);
Output:
Array (
[1100] => 1100
[4250] => 3150
[8680] => 4430
[13110] => 4430
[18280] => 5170
[25730] => 7450
[33180] => 7450
[40630] => 7450
[48860] => 8230
)
Demo on 3v4l.org
to get that one array into 2 arrays of graph co-ordinates, you can do this:
$x = array();
$y = array();
$running_total = 0;
for($i = 0; $i < count($arr); $i++){
$y[$i] = $arr[$i];
$running_total += $arr[$i];
$x[$i] = $running_total;
}
This will give you two arrays; array $x that contains a list of your X-coordinates, and $y, that gives you a list of your Y-coordinates; and you will still have access to your original $arr array, should you need to do further calculations on it. Based on your question, I think that will get you what you need.
However, if you are saying you want 1 array where the X co-ordinates are the array indexes, and the value is the array value itself, for example $y[3150] = 4250, then that is impossible; because you have duplicates in your original list, you cannot use those values as array indexes without ending up overwriting them.
(At least, not without making each array value an array itself, but that is taking things an order of magnitude above where is probably necessary)
Calculating the running total and storing the data as key-value pairs can be achieved with a foreach() and zero function calls.
Although perhaps a little unorthodox, it is valid syntax to use the "addition assignment" operator as the key of the output array. This updates the $previous value and supplies the calculated value as the key.
Code: (Demo)
$arr = [1100,3150,4430,4430,5170,7450,7450,7450,8230];
$result = [];
$previous = 0;
foreach ($arr as $value) {
$result[$previous += $value] = $value;
}
var_export($result);
// same result as #Nick's answer
Related
Newly-entered products are displayed in the last row. If there is a large amount, it is difficult to see at the bottom. How can I change the new display to the top. Thank you!
$barcodes_ary = explode(',', $barcodes);
$barcodes_hash = array ();
foreach ($barcodes_ary as $b) {
if (array_key_exists($b, $barcodes_hash)) {
$barcodes_hash[$b] += 1;
} else {
$barcodes_hash[$b] = 1;
}
}
foreach ($barcodes_hash as $b => $amount) {
if ($barcodes_ary == array(''))continue;
$ary = get_sql("SELECT * FROM Products WHERE Barcode='$b' Order by ProductName");
if ( count($ary) == 0 ) {
continue;
}
$pid = $ary[0]['ProductID'];
$pn = $ary[0]['ProductName'];
$unit = $ary[0]['UnitID'];
$ary2 = get_sql("SELECT UnitName FROM Units WHERE UnitID = '$unit'");
$unit = $ary2[0]['UnitName'];
?>
<TR>
<TD><? echo "$pn"; ?></TD>
<TD>
<INPUT TYPE=hidden NAME=productid<?=$pid?> VALUE='<?=$pid?>'>
<?
$candidates = array();
for($i=1; $i <= DropDownMaxValue; $i++) {
$candidates[]=$i;
}
//update
I use another way to solve the problem. Just display the same product.
function push_barcode() {
// alert('barcode pushing');
b = document.form1.barcode;
bs = document.form1.barcodes;
if (bs.value == "") {
bs.value = b.value;
} else { // ?? 111,333,444,... ???
bs.value = b.value;
}
}
Okay, you should be able to get the count using the keys values returned in reverse in brackets with the array.
Try the following and see if it works for you...
$ProductName = $ary[0]['ProductName'];
//--> get the count of your array
$count = count($ProductName);
//--> define an output variable to hold values
$output = null;
$i = 0;
//--> reduce count by one as key values start at 0 and count starts at 1
$count = $count - 1;
//--> subtraction and addition of $count by one to reduce warning
//--> of `undefined offset` for index on mismatched key values
while($count + 1){
//--> concatenate the values into a variable for display
$output .= $ProductName[$count];
//--> or push the reversed values back into an array
$product_name[$i] = $ProductName[$count];
//--> $product_name should now hold your values in reverse use a foreach
// use a foreach to display values in your table
$count--;
$i++;
}
I need to generate an array whose keys are not pre-defined.
I have this array:
regions = [
{
"id":1,
"name":"Alaska",
"continent_id":5,
"owner_id":3,
....
},
{
"id":2,
"name":"Greenland",
"continent_id":5,
"owner_id":7,
....
}
I want to generate
$summary = [];
for ($i = 0; $i < count($owners); $i++) {
for ($j = 0; $j < count($regions); $j++) {
if ($owners[$i]['id'] == $regions[$j]['owner_id']) {
$summary[ $regions[$j]['continent_id'] ]++; <-- NEED HELP HERE
}
}
}
So I end up with $summary containing a "key" for each continent that the user owns regions in, and how may in each continent.
The above does not work as it returns undefined index. How do I generate the array keys on the fly and keep the count?
My expected output is:
$summary = ['1' => 12, '3' => 5, '5' => 7];
$summary[1] = 12;
$summary[3] = 5;
$summary[5] = 7;
When you first encounter a particular value of 'continent_id' - or in fact any element of an array that hasn't previously been encountered, it's better to do an isset and then create it if required.
if ($owners[$i]['id'] == $regions[$j]['owner_id']) {
if ( isset($summary[ $regions[$j]['continent_id'] ]) === false ) {
$summary[ $regions[$j]['continent_id'] ] = 0;
}
$summary[ $regions[$j]['continent_id'] ]++;
}
MySQL array
CSV file array
I want to match this two different associative arrays "Url" value. Also I want remaining array value of CSV file i.e. DA, PA, MozRank, Linksln, and so on...
I hope some genius can help me
Thank you
Check this custom PHP script returns you matched url from two array
<?php
/**
* Function for match url and return data
*/
function matchArray($array1, $array2)
{
$index = 0;
$return = array();
$count1 = count($array1);
$count2 = count($array2);
for($i=0; $i < $count1; $i++)
{
for($j=0; $j < $count2; $j++)
{
if($array1[$i]['url'] == $array2[$j]['url']) {
$return[$index]['url'] = $array2[$j]['url']; // Add index which you want to get
$return[$index]['DA'] = $array2[$j]['DA']; // Add index which you want to get
$return[$index]['PA'] = $array2[$j]['PA'];
$return[$index]['MozRank'] = $array2[$j]['MozRank'];
}
$index ++;
}
}
echo "<pre>";
print_r($return); // this will return matched url form two array
}
$array1 = array(array('url' => 'AllConsuming.net' ),array('url' => 'app.brand-mention.com'),array('url' => 'www.microsoft.com'));
$array2 = array(array('url' => 'AllConsuming.net', 'DA' => 48, 'PA'=> 54.4, 'MozRank'=> 5.4),array('url' => 'www.microsoft.com', 'DA' => 31.7, 'PA'=> 54.4, 'MozRank'=> 5.4));
matchArray($array1, $array2); // calling function
?>
If you want to know which entries are indentical, proceed this way :
$array1 = array_column($ar1, 'url'); // return array('AllConsuming.net', 'http://app.brand-mention.com', 'https://www.microsoft.com', 'otherstuff')
$array2 = array_column($ar2, 'url'); // return array('AllConsuming.net', 'TravelIntelligence.net', 'otherstuff')
// compare these 2 arrays
$comp = array_intersect($aray1, $array2);
var_dump($comp); // output array('AllConsuming.net', 'otherstuff');
I have MySQL with Float Values which are pressure parametters. I need to calculate average. But the code I make returns me average "empty" in my json response.
Here is the json response I get:
{"result":{"pressure":{"min":[{"Id":"2","presion":"0","Insertado":"2016-08-16 16:20:08"},{"Id":"5","presion":"0","Insertado":"2016-08-16 18:09:04"}],"max":[{"Id":"3","presion":"55","Insertado":"2016-08-16 16:22:14"}],"avg":[]},"last_entry":{"Id":"8","presion":"50","Insertado":"2016-08-16 18:28:45"}}}
As it shows. avg give empty!.
This is code in PHP
$press_values = get_press_values($json_object->result);
// get pressure result set with respected values
$press_result = get_press_result_set_from_values($json_object->result,$press_values);
// get latest entry
$latest_entry = get_latest_date_entry($json_object->result);
// Wrap results in an array
$output_result = array(
'pressure' => $press_result,
'last_entry' => $latest_entry
);
}
Then.
function get_press_values($result){
$min = -1;
$max = -1;
$avg = -1;
// get all pressure values
$pressures = array_map(function($result_item) {
return intval($result_item->presion);
}, $result);
if($pressures){
$min = min($pressures);
$max = max($pressures);
$avg = intval(calculate_average($pressures));
}
return array(
'min' => $min,
'max' => $max,
'avg' => $avg
);
}
Then:
function get_press_result_set_from_values($array,$value){
$min_objs = array();
$max_objs = array();
$avg_objs = array();
foreach ($array as $item) {
if($item->presion == $value['min']){
$min_objs[] = $item;
}
if($item->presion == $value['max']){
$max_objs[] = $item;
}
if($item->presion == $value['avg']){
$avg_objs[] = $item;
}
}
return array(
'min' => $min_objs,
'max' => $max_objs,
'avg' => $avg_objs,
);
}
then:
function calculate_average($arr) {
$total = 0;
$count = count($arr); //total numbers in array
foreach ($arr as $value) {
$total = $total + $value; // total value of array numbers
}
$average = ($total/$count); // get average value
return $average;
}
This part in your code:
if($item->presion == $value['avg']){
$avg_objs[] = $item;
}
will only add an item if the presion perfectly matches the average, which can be very unlikely, depending on your data of course.
update: For example you have the values 50, 51, 54, 55. The average is 53. Your code will not find any $item->presion which is equal to 53, because the average doesn't need an item that has that value (in contrast to min and max).
You should check if you actually mean the median (which has to be determined in a different way ...).
update2: to get the average into your result, you have to change
$avg_objs = array(); to $avg_objs = $value['avg'];. and remove the part from your code that I posted above.
Also, if you want your average to not be an integer, you should change the line
$average = ($total/$count);
to
$average = (float)$total / $count;
and remove the intval from:
$avg = intval(calculate_average($pressures));
I wanna sum all values from my array
for example
{
"data": [
{
"message_count": 14051
},
{
"message_count": 12731
},
{
"message_count": 7867
},
{
"message_count": 6053
},
{
"message_count": 4
}
]
}
and that's my code:
<?php
$messages_count = file_get_contents('baza.html');
$json_a=json_decode($messages_count,true);
$counting_base = ($json_a['data']);
echo array_sum($counting_base);
?>
but I still get '0'. Any ideas?
Thank you very much
This is because your array is two-dimensional. array_sum() requires a one-dimensional array. To make it one-dimensional, loop through the array, and use array_sum(), like so:
$new = array();
foreach ($json_a['data'] as $key => $innerArr) {
$new[] = $innerArr['message_count'];
}
echo array_sum($new); // 40706
Online demo
Try this:
array_sum(array_column($json_a['data'], 'message_count'));
Output: 40706
live demo
alternative:
You can do it by a loop:
array_sum()
will not be working since you do not right formated array(1D array).
$sum = 0;
for($i=0; $i<count($counting_base); $i++)
{
$sum += $counting_base['message_count'];
}
echo "Total = ". $sum;