Json_encode - converting an array into a json object - php

I am currently fetching values from mysql table. The values are grabbed from a foreach loop. Then after the loop is done the array is converted into a json object. But I am having difficulties getting the json format in order to use with another api. My loop only display one result when there are two. Also I have a function that returns a hexadecimal value which is returning null when I call it inside the loop. How could I get those values in the format shown below?
header("Content-type: application/json");
//get the course list
$education_query = $db_con->prepare("SELECT a.type, COUNT(1) AS cnt
FROM academy a
GROUP BY a.type");
$education_query->execute();
$data = $education_query->fetchAll();
$output = array();
foreach ($data as $row) {
//$type = ;
$output["valueField"] = $row["type"];
$output["name"] = $row["type"];
$output["color"] = hexcode();
} // foreach ($data as $row) {
echo json_encode(array($output));
Current Result:
[{"valueField":"Upper-Secondary","name":"Upper-Secondary","color":null}]
Desired Result:
[{
valueField: "Post-Secondary",
name : "Post-Secondary",
color: "#40ae18"
},
{
valueField: "Upper-Secondary",
name : "Upper-Secondary",
color: "#aaab4b"
}]
EDIT(adding hexcode function):
function hexcode()
{
$min = hexdec("000000"); // result is 0 and sets the min-value for mt_rand
$max = hexdec("FFFFFF"); // result is 16777215 and sets the max-value for mt_rand
$random = mt_rand($min, $max); // creates a radom number between 0 and 16777215
$random_hex = dechex($random); // transforms the random number into a Hex-Code
// now the test, if the result has 6 chars
if (strlen($random_hex) != "6") // sometimes it returns an only 5, or less, char Hex-Code,
hexcode(); // so the function has to be repeat
else
echo $random_hex; // returns the Hex-Code
}

$output needs to be an array of arrays.
$addToOutput = array();
$addToOutput["valueField"] = $row["type"];
// add other fields
$output[] = $addToOutput;

your loop is displying one results because you're overwriting the array keys every time.
you can change those 3 lines
$output["valueField"] = $row["type"];
$output["name"] = $row["type"];
$output["color"] = hexcode();
to
$output[]["valueField"] = $row["type"];
$output[]["name"] = $row["type"];
$output[]["color"] = hexcode();
can you post the hexcode() function ?
EDIT
no need for all this code, you can use this :
function hexcode(){
return sprintf("#%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0,255));
}

Related

How to find the sum of the values of this time series data set?

My controller is returning a time-series array for a graph, it also needs the total views count. The array it returns is in this format, need to calculate the sum of views corresponding ot the dates.
framework: Laravel
[
{
"2021-04-30": 0,
"2021-05-01": 0,
"2021-05-02": 0,
"2021-05-03": 0,
"2021-05-04": 0,
"2021-05-05": 0,
"2021-05-06": 1
}
]
$result = $as->getVisits();
$array = json_decode($result,1);
$total = 0;
foreach($array[0] as $date => $visits)
$total += 1;
echo $total;
return [$result, $total];
This look like a JSON array, you need first to decode it in a php array and then loop it to make the sum if you want to control over the dates
$array = json_decode($json,1);
$sumVisits = 0;
foreach($array[0] as $date => $visits)
$sumVisits += 1;
echo $sumVisits;
Or if you just want to sum everything you can use array_sum as pointed out in the comments by El_Vanja
$array = json_decode($json,1);
echo array_sum(array[0]);

PHP Replace specific values inside formula

I have a formula where some of the data needs to be replaced by MYSQLI query results.
The formula can look like:
100+400-600-700
The numbers in the formula will match a specific table line in the DB and output correct value, for example:
121000+1000-8000-2000
I've tried to extract all the special characters from the original string in order to get the correct DB result via MYSQLI using formula:
preg_match_all('!\d+!', $rf, $matches);
foreach ($matches as $key1 => $value) {
//Declare summarization of TOT rows
$TOT = 0;
foreach ($value as $single) {
$querymatch = mysqli_query($mysqli, "SELECT rowMainAccount FROM reportTable_rowDefinitions WHERE rowCode = '$single' AND reportID = $rowDefinition");
$arraymatch = mysqli_fetch_array($querymatch);
$TOTaccount = $arraymatch['rowMainAccount'];
//Fetch values from FinancialTransactions
//Fetch values
$queryTOT = mysqli_query($mysqli, "SELECT SUM(debit) AS debitTOT, SUM(credit) AS creditTOT FROM FinancialTransactions WHERE mainAccount = $TOTaccount AND entity = $org AND date BETWEEN '$newStartDate' AND '$newEndDate'");
$arrayTOT = mysqli_fetch_array($queryTOT);
$TOTcred += $arrayTOT['creditTOT'];
$TOTdeb += $arrayTOT['debitTOT'];
}
$TOT += $TOTdeb - $TOTcred;
}
echo $TOT; //Returns values
This will only replace the numbers in the original string giving result as
121000100080002000
from foreach loop.
How can I put the returned values from DB into the original formula to acieve the correct output as
121000+1000-8000-2000
?
Use preg_replace_callback and in the callback you can get the appropriate value and return it to place it in the original string.

Array push not working in a function? PHP

I'm Trying to get 5 dates ($completion_date) into an array I have a list I'm looping through passing the $completion_date to the function below there are multiple instances of the same $completion_date in the list but I only want one of each in the array $completion_dates = []; so each time I search the array using array_search($completion_date, $completion_dates); and if the current $completion_date isn't there I want to add it to the array and if it is I want to modify $completions and $payouts at the same position in their respective arrays. My problem is array_push doesn't seem to push all the dates? only one?
And I've checked the if statement that array_push is in and it's running the else clause every time (as array_push isn't working to change that);
function sortResults($completion_date, $payout){
global $completion_dates, $completions, $payouts;
$completion_dates = [];
$completions = [0,0,0,0,0]; // not in use
$payouts = [0,0,0,0,0]; // not in use
// check is $completion_date is in $completion_dates array and get position if so.
$position = array_search($completion_date, $completion_dates);
if ($position) {
// update $payouts and $completions # same $position.
}else{
// add $completion_date to $completion_dates array.
array_push($completion_dates, $completion_date);
}
}
var_dump($completion_dates);
outputs: array(1) { [0]=> string(10) "22/01/2017" }
But should output four other dates "18/01/2017", "19/01/2017", "20/01/2017", "21/01/2017" as well?
the data i'm looping through is escaping the dates like so {"completion_date":"18\/01\/2017","0":"18\/01\/2017","payout":"13.20","1":"13.20"} not sure if it matters, it really shouldn't?
Because you overwrite $completion_dates each time in your function.
function sortResults($completion_date, $payout)
{
global $completion_dates, $completions, $payouts;
$completion_dates = []; <----------------------- HERE
$completions = [0, 0, 0, 0, 0]; // not in use
$payouts = [0, 0, 0, 0, 0]; // not in use
// check is $completion_date is in $completion_dates array and get position if so.
$position = array_search($completion_date, $completion_dates);
if ($position) {
// update $payouts and $completions # same $position.
} else {
// add $completion_date to $completion_dates array.
array_push($completion_dates, $completion_date);
}
}

Calculation error with Numbers containing more than 3 Digits

I'm importing prices from a database using the following code:
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$product = array();
$result = $mysqli->query("SELECT Name, WPrice as price, APrice as a_price from my_table where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
$product_name = $row['Name'];
// find all keys in $item_array which value is the products
$keys = array_keys($item_array, $product_name);
foreach ($keys as $key) {
// add values for these keys
$product[$key + 1]["Name"] = $row['Name'];
$product[$key + 1]["price"] = number_format($row['price'],2);
$product[$key + 1]["a_price"] = number_format($row['a_price'],2);
}
}
And then I apply the following functions:
function price($m) {
global $product,$i;
if ($m == "a") {
$value = $product[$i]["a_price"];
}
else {
$value = $product[$i]["price"]; //
}
return $value;
}
I'm trying to use the following comparison:
<?php if ( price( a )< price( default ) ) {echo "Smaller";} ?>
To echo Smaller whenever the price of A is smaller than the default price.
It works fine for prices in the range of 0 to 999.99, but for when a price of 1,000 or more is involved, I'm getting the opposite results (it echos smaller when bigger and vice-versa)
What is causing this problem?
You're comparing strings because that's what you stored in $product["price"] and $product["a_price"] (the function number_format() returns a string value). For numbers >= 1000, those strings include commas, which breaks the comparison.
Compare the numeric values and don't call number_format() until you need to display the values.

PHP mysql select only the rows with highest value (random character numeric order)

Example:
thisisline>and>1
thisisanother>line>something>13
just>another>line>143
short>11
I have this kind of data in my database on column 'profile'. What I need is to pick columns user_name and profile from the database where profile has the 5 highest values after the last occurance of the '>'
First you have to extract the numbers from your lines. Afterwards, order them and take the ones you want.
$lines = "thisisline>and>1
thisisanother>line>something>13
just>another>line>143
short>11";
$tmp = explode("\n", $lines); //separate lines
$numbers = array();
foreach($tmp as $line)
{
$numbers[] = substr($line, strrpos($line, ">") + 1); //extract number
}
rsort($numbers); //order your results
$count = 2; //define the count of results
$result = array_slice($numbers, 0, $count); //just take the ones which you want
var_dump($result);
You'll get your result as an array.
Working example here in a php sandbox.
Do like this.
Get all lines into an array, parse them, store the last value in an array, sort it revrse mode, and do what you want.
$lines = 'thisisline>and>1
thisisanother>line>something>13
just>another>line>143
short>11';
define('NUM_TO_GET', 2); //Get the two highest. Rewrite it to 5!
$array = explode("\n", $lines);
$results = array();
foreach ($array as $line) {
$tmp = explode('>', $line);
$results [] = $tmp[count($tmp) - 1];
}
rsort($results);
for ($i = 0; $i < NUM_TO_GET; $i++) {
if (isset($results[$i])) {
echo $results[$i] . "<br />";
} else {
break;
}
}
$theNumber = substr($string, strrpos($string, ">")+1);
This should give you the number for each line. Then, you just compare the numbers.

Categories