I am trying to parse a JSON file for the first time ever and insert the information into my database. The problem is that this object/array is multidimensional, so $number = stats[0] is getting values on each level of the array. This is a link to the JSON file. I want to avoid everthing but the data: values that I exploded with PHP. Here is a link to my output right now. If you look at my output, I am only interested in the 8,C,J. Pavelski and 26. Those are the values I want in my database.
$json = file_get_contents("http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json");
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
$stats = explode(",", $val);
$number = $stats[0];
$position = $stats[1];
$name = $stats[2];
$gp = $stats[3];
$goals = $stats[4];
$assists = $stats[5];
$points = $stats[6];
$plsmns = $stats[7];
$pim = $stats[8];
$shots = $stats[9];
$toi = $stats[10];
$pp = $stats[11];
$sh = $stats[12];
$gwg = $stats[13];
$ot = $stats[14];
echo $number." ".$position." ".$name." ".$points."<br />";
/* $query = "INSERT INTO stats2015_2016 ('number','position','name','gp','goals','assists','points','plsmns','pim','shots', 'toi', 'pp', 'sh', 'gwg', 'ot')
VALUES ('$number','$position','$name','$gp','$goals','$assists','$points','$plsmns','$pim','$shots','$toi','$pp','$sh','$gwg','$ot')";
$result= $db->query($query); */
}
Thank you
$json = file_get_contents('http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json');
$json = json_decode($json, TRUE);
$skaterData = $json['skaterData'];
$goalieData = $json['goalieData'];
foreach($skaterData as $d){
$sk = explode(',', $d['data']);
$number = $sk[0];
$position = $sk[1];
$name = $sk[2];
$points = $sk[6];
echo $number." ".$position." ".$name." ".$points."<br />";
}
repeat for goalie data as required
Related
Is there a way I can Array_chunk mysqli results, I am looping messages from a table and later pass the values into a method "Sms" The method will create a List of Sms objects which I pass through a function SendBatchSMS. my API end points can only allow 100 call per request.
I have tried array chunking the list into "$sms" which seams to work well when I print_r($sms), but when echo the response, it returns only 48/249 responses regardless of the size specified in the array_chunk function. My question is, is there a better option to achieve this, something like array_chunking the mysqli results instead of the array list?
$query_sch = "SELECT * FROM ct_queue";
$sch_result = mysqli_query($mysqli, $query_sch);
$rows[] = mysqli_fetch_array($sch_result);
$count = mysqli_num_rows($sch_result);
foreach($sch_result as $value)
{
$phone = $value['phone'];
$sender = $value['sender'];
$message = $value['message'];
$user_id = $value['user_id'];
$link_id = NULL;
$correlator = 'correlator_string';
$endpoint = 'example.com';
$token = "token_string";
// $list = array();
$version = "v1"; //DONT change unless you are using a different version
$instance = new BonTech($token, $version);
$list[] = new Sms($sender, $phone, $message, $correlator, null, $endpoint);
}
$row_chunks = array_chunk($list, 100);
foreach ($row_chunks as $chunk){
$sms = array();
////////here we have 100 messages on each chunk
///////Loop through the messages in side the chunk
foreach ($chunk as $row) {
$sms[] = ($row);
}
// print_r($sms);
}
$response = call_user_func_array(array($instance, "sendBatchSMS"), $sms);
$response = json_encode($response, true);
$results = json_decode($response, true);
print_r($response);
You're using $sms after the foreach loop is done. So it will only contain the last chunk. You need to use it inside the loop.
There's also no need to use a loop to copy $chunk to $sms.
You're also skipping the first row of results because of your call to mysqli_fetch_array($sch_result) before the first foreach loop.
$instance doesn't seem to be dependent on $value, so it shouldn't be in the foreach loop.
$query_sch = "SELECT * FROM ct_queue";
$sch_result = mysqli_query($mysqli, $query_sch);
$list = array();
foreach($sch_result as $value)
{
$phone = $value['phone'];
$sender = $value['sender'];
$message = $value['message'];
$user_id = $value['user_id'];
$link_id = NULL;
$correlator = 'correlator_string';
$endpoint = 'example.com';
$list[] = new Sms($sender, $phone, $message, $correlator, null, $endpoint);
}
$token = "token_string";
$version = "v1"; //DONT change unless you are using a different version
$instance = new BonTech($token, $version);
$row_chunks = array_chunk($list, 100);
foreach ($row_chunks as $sms){
$response = call_user_func_array(array($instance, "sendBatchSMS"), $sms);
print_r($response);
}
My string is
"invoice = [[invoice_no]]
customer = [[customer]]
item = [[item]]"
How can i do upper string to covert the following with php?
"invoice = " $data->invoice_no
"customer = " $data->customer
"item = " $data->item
I already created one function for same type of parsing, it replaces {{item}} by give data like $data['item']. here is example , you can change according to your requirement.
<?php
function putValuesInHTML($html_form,$reportData){
preg_match_all('/{{([A-Za-z0-9_ ]+?)}}/', $html_form, $fields);
$arrInHtml = array();
$valsForHtml = array();
foreach ($fields[1] as $key => $value) {
if(isset($reportData[$value])){
$arrInHtml[] = "{{".$value."}}";
$valsForHtml[] = $reportData[$value];
}
}
$result = str_replace($arrInHtml,$valsForHtml,$html_form);
/*Eval start*/
preg_match_all('/{{=([A-Za-z0-9+\-\/{}* ]+?)=}}/', $result, $evals);
$arrInHtml = array();
$valsForHtml = array();
foreach ($evals[1] as $key => $value) {
$eval = "00";
$arrInHtml[] = "{{=".$value."=}}";
eval("\$eval= ".$value.";");
$valsForHtml[] = $eval;
}
$reportHTML = str_replace($arrInHtml,$valsForHtml,$result);
return $reportHTML;
}
$str = "invoice = {{invoice_no}}
customer = {{customer}}
item = {{item}}";
$data = ["invoice_no"=>"111","customer"=>"Niklesh Raut","item"=>"iphone"] ;
$newStr = putValuesInHTML($str,$data);
echo $newStr;
?>
Live demo
Input :
invoice = {{invoice_no}}
customer = {{customer}}
item = {{item}}
Output for $data = ["invoice_no"=>"111","customer"=>"Niklesh Raut","item"=>"iphone"] :
invoice = 111
customer = Niklesh Raut
item = iphone
I have a query that I execute, then I use
while($row = $result->fetch_assoc()){
$data[] = $row;
I know this is grotesque, but I'm unsure how to make this an object or a multidimensional array so I just made something like this..
$NUH2016 = array();
$NUH2017 = array();
$NUH2018 = array();
$NUH2019 = array();
$NUH2020 = array();
$NUH2021 = array();
$RBN2016 = array();
$RBN2017 = array(); ...
...$GDT2019 = array();
$GDT2020 = array();
$GDT2021 = array();
while($row = $result->fetch_assoc()){
$data[] = $row;
if($row['Location'] == 'NUH' && $row['Year'] == '2016'){
$NUH2016[] = $row['P_1'];
$NUH2016[] = $row['P_2'];
$NUH2016[] = $row['P_3'];
$NUH2016[] = $row['P_4'];
}
if($row['Location'] == 'NUH' && $row['Year'] == '2017'){
$NUH2017[] = $row['P_1'];
$NUH2017[] = $row['P_2'];
$NUH2017[] = $row['P_3'];
$NUH2017[] = $row['P_4'];
}
//...for all locations and years
...then
$content = array();
$results = array();
$NUH2016_total = array_sum($NUH2016);
$NUH2017_total = array_sum($NUH2017);
$NUH2018_total = array_sum($NUH2018);
$NUH2019_total = array_sum($NUH2019);
$NUH2020_total = array_sum($NUH2020);
$NUH2021_total = array_sum($NUH2021);
$results['NUH~2016'] = $NUH2016_total;
$results['NUH~2017'] = $NUH2017_total;
$results['NUH~2018'] = $NUH2018_total;
$results['NUH~2019'] = $NUH2019_total;
$results['NUH~2020'] = $NUH2020_total;
$results['NUH~2021'] = $NUH2021_total;
$RBN2016_total = array_sum($RBN2016);
$RBN2017_total = array_sum($RBN2017);
$RBN2018_total = array_sum($RBN2018);
$RBN2019_total = array_sum($RBN2019);
$RBN2020_total = array_sum($RBN2020);
$RBN2021_total = array_sum($RBN2021);
$results['RBN~2016'] = $RBN2016_total;
$results['RBN~2017'] = $RBN2017_total;
$results['RBN~2018'] = $RBN2018_total;
$results['RBN~2019'] = $RBN2019_total;
$results['RBN~2020'] = $RBN2020_total;
$results['RBN~2021'] = $RBN2021_total;
...etc
$content['Results'] = $results;
$response = json_encode($content);
echo $response;
So what I want to do is make an object or associative array that looks like this.
content {
produced hours{
nuh{ 2016:16,000
2017:8,000
...
}
rbn{ 2016:9,000
2017:whatever
....
}
man hours{
nuh{ 2016:4,000
2017:2,000
...
}
rbn{ 2016:1,000
2017:more stuff
....
}
but I'm pretty new to php objects. How can I refactor it so that I don't have to initialize every single empty array, have a bunch of if statements to make each entry from the query fit into an array to be summed, and then put it all into an object at the end to get back from an ajax success function?
There's no need to declare so many arrays. Simply change your while() loop in the following way,
$resultArr = array();
while($row = $result->fetch_assoc()){
$tmpArr = array($row['P_1'], $row['P_2'], $row['P_3'], $row['P_4']);
$sumTotal = array_sum($tmpArr);
$tmpArr['sumTotal'] = $sumTotal;
$resultArr[$row['Location']][$row['Year']][] = $tmpArr;
}
Later, apply json_encode() on the result array like this,
$json = json_encode($resultArr);
Sidenote: If you want to see the complete array structure, do var_dump($resultArr);
You can have an array of arrays, so you don't need to manually assign them all.
$LocationAndYears;
while($row = $result->fetch_assoc())
{
$LocationAndYears[$row['Location']] [$row['Year']] [0] = $row['P_1'];
$LocationAndYears[$row['Location']] [$row['Year']] [1] = $row['P_2'];
$LocationAndYears[$row['Location']] [$row['Year']] [2] = $row['P_3'];
$LocationAndYears[$row['Location']] [$row['Year']] [3] = $row['P_4'];
$LocationAndYears[$row['Location']] [$row['Year']] ['sum'] = array_sum($LocationAndYears[$row['Location']] [$row['Year']]);
}
echo $LocationAndYears['NUH']['2012'][0];
echo "Sum for 2012 at NUH:" . $LocationAndYears['NUH']['2012']['sum'];
print_r($LocationAndYears);
Without writing the whole thing, look into multi-dimensional arrays.
Something like this maybe...
But really I think the answer to this is to point you at multi-dimensional arrays as it's very vague
$data = array();
while($row = $result->fetch_assoc()){
$location = $row['Location'];
$year = $row['Year'];
$data[$location] = $data[$location] ? $data[$location] : array();
$data[$location][$year] = $data[$location][$year] ? $data[$location][$year] : array();
$data[$location][$year][] = $row['P_1'];
$data[$location][$year][] = $row['P_2'];
$data[$location][$year][] = $row['P_3'];
$data[$location][$year][] = $row['P_4'];
}
How would you transform a monodimensional array into a multidimensional array in PHP? Suppose you have something like this
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
And you want a function to transform it into
$array['breakfast'] = 'milk';
$array['meal']['firstdish'] = 'pasta';
$array['meal']['seconddish']['maincourse'] = 'veal';
$array['meal']['seconddish']['dressing'] = 'fries';
$array['meal']['dessert'] = 'pie';
The same function should of course transform
$tire['ean'] = '3286347717116';
$tire['brand.maker'] = 'BRIDGESTONE';
$tire['brand.model.name'] = 'POTENZA';
$tire['brand.model.variant'] = 'RE 040 RFT * SZ';
into
$tire['ean'] = '3286347717116';
$tire['brand']['maker'] = 'BRIDGESTONE';
$tire['brand']['model']['name'] = 'POTENZA';
$tire['brand']['model']['variant'] = 'RE 040 RFT * SZ';
I was thinking of using explode, then eval on the results, but eval always feels like cheating to me and I guess it would keep my code from running in HipHop.
The reason I want to do this is that I have to export lots of different tables from a database into XML files, and I already have a robust function that turns a multidimensional array into XML.
Like this:
function build(array &$trg, array $k,$key,$value) {
$p = &$trg;
while ( !empty($k) ) {
$nk = array_shift($k);
if ( !isset($p[$nk]) ) {
$p[$nk] = [];
}
$p = &$p[$nk];
}
$p[$key] = $value;
return $p;
}
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
$out = [];
foreach ($array as $key => $value ) {
$path = explode('.',$key);
$last = array_pop($path);
build($out,$path,$last,$value);
}
print_r($out);
You were on the right track with explode, but there's no need to use eval. Once you've got the pieces of the keys available, you can loop over them and incrementally assign a pointer into a new array:
<?php
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
$result = [];
$target = null;
foreach ($array as $key => $value) {
// Start by targeting the base of our resulting array
$target =& $result;
// Break the keys apart into pieces
$keyParts = explode('.', $key);
// Assign new target based on indexing into the result array one "piece" at a time
while ($part = array_shift($keyParts)) {
$target =& $target[$part];
}
// Finally, assign the value to our target
$target = $value;
}
See https://eval.in/625627
I have a problem with array push.I cant get the all data from the array array.I want to get like this format.
[["username","average"],["aa",2.34],["bb",6.7],["hh",9.8]]
here is my code
while($acc_rs = mysql_fetch_array($acc_qry))
{
$acc_cnt = $acc_rs['Total_login'];
$time_stamp = $acc_rs['last_logged'];
$avg_login = $acc_rs['avg'];
$name = $acc_rs['name'];
$ji = array();
$sal = array("username","average");
$kk = array($name,$avg_login);
array_push($ji,$sal,$kk);
}
array_push($da,$new,$average);
$result = array(array('username', 'average'));
while ($row = mysql_fetch_assoc($acc_qry)) {
$result[] = array($row['name'], $row['avg']);
}
echo json_encode($result);