$_POST values changing or disappearing inside foreach loop - php

Prior to this foreach loop $_POST['encounterName'] contains a predefined name. Inside the loop its value changes to ".json" so the first string in file_put_contents reads ".json.json". As well $_POST['basicTrainingSectionSlide'], $_POST['basicTrainingContentHeader'], and
$_POST['basicTrainingContentText'] lose their values. After the foreach loop, all values go back to normal. What is happening here?
$i = 0;
$j = 0;
foreach($_POST['Sections'] as $order){
if(strcmp($order, "Section") == 0){
file_put_contents($_POST['encounterName'].".json", "\t\t[\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"Section\",\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"".$_POST['basicTrainingSectionSlide'][$i]."\"\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t],\n", FILE_APPEND);
$i++;
}
else if(strcmp($order, "Text") == 0){
file_put_contents($_POST['encounterName'].".json", "\t\t[\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"Text\",\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"".$_POST['basicTrainingContentHeader'][$j]."\"\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"".$_POST['basicTrainingContentText'][$j]."\"\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t],\n", FILE_APPEND);
$j++;
}
}
This is what the $_post array contains:
array(11) { ["encounterName"]=> string(8) "Violence" ["encounterHint"]=> string(0) "" ["basicTrainingSectionSlide"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "6" } ["basicTrainingContentHeader"]=> array(2) { [0]=> string(1) "2" [1]=> string(1) "4" } ["basicTrainingContentText"]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "5" } ["contextText_1"]=> string(0) "" ["contextText_2"]=> string(0) "" ["contextText_3"]=> string(0) "" ["contextText_4"]=> string(0) "" ["contextText_5"]=> string(0) "" ["submit_form"]=> string(6) "Submit" } array(11) { ["encounterName"]=> string(8) "Violence" ["encounterHint"]=> string(0) "" ["basicTrainingSectionSlide"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "6" } ["basicTrainingContentHeader"]=> array(2) { [0]=> string(1) "2" [1]=> string(1) "4" } ["basicTrainingContentText"]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "5" } ["submit_form"]=> string(6) "Submit" }
Some added information:
-The form that is filled out sends its post data to a separate php file for processing.
-The $_POST['Sections'] is sent via this function:
function returnValues() {
$.ajax({
type: "POST",
url: "final.php",
data:{ Sections: $sectionOrder },
success: function(data){
console.log(data);
}
})
}
from a .js file onsubmit of the form tag.

Assuming that $_POST['Sections'] contains something like:
array(11) {
["encounterName"]=> string(8) "Violence"
["encounterHint"]=> string(0) ""
["basicTrainingSectionSlide"]=> array(2) {
[0]=> string(1) "1"
[1]=> string(1) "6" }
["basicTrainingContentHeader"]=> array(2) {
[0]=> string(1) "2"
[1]=> string(1) "4" }
["basicTrainingContentText"]=> array(2) {
[0]=> string(1) "3"
[1]=> string(1) "5" }
["contextText_1"]=> string(0) ""
["contextText_2"]=> string(0) ""
["contextText_3"]=> string(0) ""
["contextText_4"]=> string(0) ""
["contextText_5"]=> string(0) ""
["submit_form"]=> string(6) "Submit"
}
array(11) {
["encounterName"]=> string(8) "Violence"
["encounterHint"]=> string(0) ""
["basicTrainingSectionSlide"]=> array(2) {
[0]=> string(1) "1"
[1]=> string(1) "6" }
["basicTrainingContentHeader"]=> array(2) {
[0]=> string(1) "2"
[1]=> string(1) "4" }
["basicTrainingContentText"]=> array(2) {
[0]=> string(1) "3"
[1]=> string(1) "5" }
["submit_form"]=> string(6) "Submit"
}
I would do something like this:
$i = 0;
$j = 0;
foreach($_POST['Sections'] as $order){
$fn = $order['encounterName'] . ".json";
$appText = "";
if(strcmp($order, "Section") == 0){
$appText .= "\t\t[\n";
$appText .= "\t\t\t\"Section\",\n";
$appText .="\t\t\t\"" . $order['basicTrainingSectionSlide'][$i] . "\"\n";
$appText .= "\t\t],\n";
file_put_contents($fn, $appText, FILE_APPEND);
$i++;
} elseif(strcmp($order, "Text") == 0){
$appText .= "\t\t[\n";
$appText .= "\t\t\t\"Text\",\n";
$appText .= "\t\t\t\"" . $order['basicTrainingContentHeader'][$j] . "\"\n";
$appText .= "\t\t\t\"" . $order['basicTrainingContentText'][$j] . "\"\n";
$appText .= "\t\t],\n";
file_put_contents($fn, $appText, FILE_APPEND);
$j++;
}
}
Since you are in a foreach loop and iterating over the array $_POST['Sections'], to call the elements of that array, you need to use $order. That is how you defined the loop. You kept calling $_POST and those indexes shouldn't exist.
If you were using $_POST, the first occurrence of encounterName would be located at $_POST['Sections'][0]['encounterName'] and would contain the string Violence. So, in the loop, $fn = $order['encounterName'].".json"; should be assigned Violence.json as a String.
I am unsure what the if statement is looking for. Since $order is an Array, not a String, strcmp() should return NULL. See notes here. Since both if statements would fail, your file would not be appended in either case. Please comment if you want to clarify that.
I tested the following on http://phpfiddle.org/lite :
<?php
$order = array();
if(strcmp($order, "Section")){
echo "Success";
} else {
echo "Fail";
}
?>
I got the following results:
E_WARNING : type 2 -- strcmp() expects parameter 1 to be string, array given -- at line 5
Fail
This code is untested.

Related

Array data manipulations PHP

I get from my DB data in format like this:
array(12) {
[0]=>
array(4) {
["id"]=>
string(1) "1"
["count"]=>
string(5) "78984"
["month"]=>
string(1) "6"
["hours"]=>
string(10) "10580.0833"
}
[1]=>
array(4) {
["id"]=>
string(1) "2"
["count"]=>
string(5) "64174"
["month"]=>
string(1) "6"
["hours"]=>
string(9) "6866.8333"
}
[2]=>
array(4) {
["id"]=>
string(1) "3"
["count"]=>
string(5) "31032"
["month"]=>
string(1) "6"
["hours"]=>
string(9) "3700.9167"
}
[3]=>
array(4) {
["id"]=>
string(1) "1"
["count"]=>
string(5) "91114"
["month"]=>
string(1) "7"
["hours"]=>
string(10) "11859.6000"
}
...
Each of array inside has a key: "id". It mostly look values from 1 to 3. I would like to create a new array based on this "ids" that would look like this:
array("number of unique ids") {
[0]=> "for id = 0"
array(12) {
int() count/hours
int() count/hours
int() count/hours
...
}
[1]=> "for id = 1 and so on..."
array(12){
....
}
I`ve been trying to do it like this:
$data1 = [];
$data2 = [];
$data3 = [];
foreach($data as $key => $record){
if($record['id'] == 1){
array_push($data1, $record['count']/$record['hours']);
}else if($data['id_zmiana'] == 2){
array_push($data2, $record['count']/$record['hours']);
}else{
array_push($data3, $record['count']/$record['hours']);
}
}
$raport = array_merge($data1, $data2, $data3);
And that would work, but it doesn`t look good in my opinion, beacuse what if the id change to some big number.
Yeah, having separate arrays for each ID is not a good idea. How about:
$raport = [];
foreach ($data as $record) {
$raport[$record['id']][] = $record['count'] / $record['hours']);
}
Simple, and straight to the point.
Haven't tested it. Next time try to use var_export() to export the data you put in your question. That way we can actually use it, without having to rewrite it completely.

Search with PHP inside MongoDB

Im trying many days now to select data from this db
[1]: https://i.stack.imgur.com/QA34L.jpg
I want to print for example all comments
echo $comment['username']." | "; \ Alex | Alex
My php code so far:
[![$m= new MongoDB\Client ("mongodb://127.0.0.1/");
$db = $m->stores;
$collection = $db->storeinfo;][1]][1]
$storez = $collection->find(array("Products.pTHUMBNAIL" => $pThumb));
$o=1;
$afm=array();
foreach ($storez as $stor) {
$afm[$o] = $stor['AFM'];
$record = $collection->findOne(array(
"AFM" => $afm[$o],"Products.pTHUMBNAIL" => $pThumb));
foreach ($record['Products'] as $pro){
if($pThumb == $pro['pTHUMBNAIL']){
echo $temp = $pro['pID']." ";
foreach($pro as $pro1['pCOMMENTS']) {
foreach($pro1 as $com['Comment']) {
var_dump($com['Comment']);
/*
foreach($com as $comment) {
echo $comment['username'];
}
*/
}
}
}
}
$o += 1;
}
It seems that i just cannot find the correct foreach to loop through my Comment array
var_dump output:
099360111/1 object(MongoDB\BSON\ObjectId)#55 (1) { ["oid"]=> string(24) "6003403a695900000c002649" } string(11) "099360111/1" string(9) "Old Skool" string(2) "75" string(4) "Vans" string(25) "Leather and textile upper" string(2) "44" string(18) "Men/Shoes/Trainers" string(52) "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg" string(1) "7" object(MongoDB\Model\BSONArray)#65 (1) { ["storage":"ArrayObject":private]=> array(1) { [0]=> object(MongoDB\Model\BSONDocument)#10 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#73 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#45 (1) { ["milliseconds"]=> string(13) "1611028053000" } ["text"]=> string(21) "1st comment from user" ["rating"]=> string(1) "4" } } } } } } 099360666/1 object(MongoDB\BSON\ObjectId)#44 (1) { ["oid"]=> string(24) "6006563a3f1c0000c80034a8" } string(11) "099360666/1" string(12) "old school 2" string(2) "50" string(4) "Vans" string(11) "black/white" string(8) "42,43,43" string(18) "Men/Shoes/Trainers" string(52) "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg" string(1) "6" object(MongoDB\Model\BSONArray)#79 (1) { ["storage":"ArrayObject":private]=> array(2) { [0]=> object(MongoDB\Model\BSONDocument)#7 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#39 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#68 (1) { ["milliseconds"]=> string(13) "1611028089000" } ["text"]=> string(21) "1st comment from user" ["rating"]=> string(1) "4" } } } } [1]=> object(MongoDB\Model\BSONDocument)#78 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#77 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#76 (1) { ["milliseconds"]=> string(13) "1611030745000" } ["text"]=> string(8) "good!!!!" ["rating"]=> string(1) "5" } } } } } }
What about this?
After echo $temp = $pro['pID']." ";
foreach($pro['pCOMMENTS'] as $comments) {
foreach ($comments['Comment'] as $comment) {
echo $comment['text'];
}
}
You used foreach() bad: the index should be added to the first parameter, not in the 'as' part.
Also it helps if you use more clear variable names. That doesn't take too much, but makes it more readable and easy to debug.
After echo $temp = $pro['pID']." ";
foreach($pro['pCOMMENTS'] as $comments) {
foreach($comments as $comment) {
echo $comment['text'];
}
}

How to fetch arrays with string in php

how can i fetch data in an arrays with gives null value if null
here is my data I var_dump($showStatus); I want to print out . $showStatus[0]['title']
string(0) ""
array(2) {
[0]=>
array(7) {
["id"]=>
string(1) "1"
["container_id"]=>
string(1) "3"
["title"]=>
string(51) "waitting"
}
[1]=>
array(7) {
["id"]=>
string(1) "2"
["container_id"]=>
string(1) "3"
["title"]=>
string(72) "getting"
}
}
array(1) {
[0]=>
array(7) {
["id"]=>
string(1) "4"
["container_id"]=>
string(1) "7"
["title"]=>
string(51) "getting"
}
}
The reason that I've string because in my models I want to print "" or NULL when it don't have data here is my models
public function showStatus($id){
$sql = 'SELECT * FROM status WHERE container_id = '.$id;
if($this->query_rows( $sql )) {
return $this->query_rows($sql);
} else {
return "";
}
}
I try to use
foreach ($getListData as $k) {
}
but it said Warning: Invalid argument supplied for foreach()
Try this:
if(!empty($getListData) )
{
foreach ($getListData as $k) {
print_r($k);
}
}
else {
echo "NULL";
}

parse php file and get dates

I am trying to parse a csv file in php to try and figure out how to get all data between some dates and the sort according to the date in ascending order but I am not able to sort the date column or I have no idea what format it is in please help
ID Reg Date FirstName LastName
1 1278336015 Sergio Roberto
2 1395656121 Ray Wilkins
3 1300276526 Trueman Ted
4 1374087492 Volt John
Please assist thanks
Okay, just for fun.
1. Parse the Data:
You could load the CSV data into an associative array like this (admittedly not very sophisticated, no error checking, validation etc):
$file = file_get_contents('CSV.csv'); // load csv into string
$rows = explode(PHP_EOL, $file); // break each line into array
$data = Array(); // where we'll store the data
foreach ($rows as $i => $row) {
$fields = explode(',', $row); // break each field into array
foreach ($fields as $col => $val) {
if ($i == 0) {
$names[] = $val; // headers in first row
} else {
$colName = $names[$col];
if ($colName == 'Reg Date') $val = date('Y-m-d H:i:s', $val);
$data[$i - 1][$colName] = $val;
}
}
}
So with your sample data above, you get:
array(4) {
[0]=>
array(4) {
["ID"]=>
string(1) "1"
["Reg Date"]=>
string(19) "2010-07-05 06:20:15"
["FirstName"]=>
string(6) "Sergio"
["LastName"]=>
string(7) "Roberto"
}
[1]=>
array(4) {
["ID"]=>
string(1) "2"
["Reg Date"]=>
string(19) "2014-03-24 03:15:21"
["FirstName"]=>
string(3) "Ray"
["LastName"]=>
string(7) "Wilkins"
}
[2]=>
array(4) {
["ID"]=>
string(1) "3"
["Reg Date"]=>
string(19) "2011-03-16 04:55:26"
["FirstName"]=>
string(7) "Trueman"
["LastName"]=>
string(3) "Ted"
}
[3]=>
array(4) {
["ID"]=>
string(1) "4"
["Reg Date"]=>
string(19) "2013-07-17 11:58:12"
["FirstName"]=>
string(4) "Volt"
["LastName"]=>
string(4) "John"
}
}
2. Sort the Data:
You can use usort() to sort by the timestamp column.
usort($data, function ($a, $b) {
if ($a['Reg Date'] == $b['Reg Date']) return 0;
return ($a['Reg Date'] < $b['Reg Date']) ? -1 : 1;
});
Results:
===After Sorting:===
array(4) {
[0]=>
array(4) {
["ID"]=>
string(1) "1"
["Reg Date"]=>
string(19) "2010-07-05 06:20:15"
["FirstName"]=>
string(6) "Sergio"
["LastName"]=>
string(7) "Roberto"
}
[1]=>
array(4) {
["ID"]=>
string(1) "3"
["Reg Date"]=>
string(19) "2011-03-16 04:55:26"
["FirstName"]=>
string(7) "Trueman"
["LastName"]=>
string(3) "Ted"
}
[2]=>
array(4) {
["ID"]=>
string(1) "4"
["Reg Date"]=>
string(19) "2013-07-17 11:58:12"
["FirstName"]=>
string(4) "Volt"
["LastName"]=>
string(4) "John"
}
[3]=>
array(4) {
["ID"]=>
string(1) "2"
["Reg Date"]=>
string(19) "2014-03-24 03:15:21"
["FirstName"]=>
string(3) "Ray"
["LastName"]=>
string(7) "Wilkins"
}
}
3. Filter the Data:
And you can use array_filter to filter the results down. I created a class to handle this (as described by #jensgram answer here)
$from = '2011-01-01';
$to = '2013-12-31';
$filtered = array_filter($data, Array(new compareDates($from, $to), 'isInRange'));
Results:
===After Filtering [2011-01-01 - 2013-12-31]:===
array(2) {
[1]=>
array(4) {
["ID"]=>
string(1) "3"
["Reg Date"]=>
string(19) "2011-03-16 04:55:26"
["FirstName"]=>
string(7) "Trueman"
["LastName"]=>
string(3) "Ted"
}
[2]=>
array(4) {
["ID"]=>
string(1) "4"
["Reg Date"]=>
string(19) "2013-07-17 11:58:12"
["FirstName"]=>
string(4) "Volt"
["LastName"]=>
string(4) "John"
}
}
Here's the simple class I used:
class compareDates
{
function __construct($from, $to)
{
$this->from = $from;
$this->to = $to;
}
function isInRange($ele)
{
if ($ele['Reg Date'] >= $this->from && $ele['Reg Date'] <= $this->to) {
return TRUE;
}
return FALSE;
}
}
NOTE: for the purpose of being able to see the date/time, I stored as
a string. But you would normally just use the numeric value to sort
by. I mention this to say that if you change the format of the date
string, it could break the sorting.

use persistent connection to grab data

Hi all i am grabbing around 1.3k of record from Steam's database and I am wondering how I can speed up my script.
Currently I use file_get_contents on their API url in a loop for each app's ID (so this is sending 1.3k requests which as you can imagine is painfully slow).
Is there a better way? We used to lump all the app's id's together, but they have removed that ability it seems we have to do it one at a time now, and it's not good.
This is my code showing the loop:
foreach($Chunks as $Game)
{
if ($Game['bundle'] == 0)
{
$Subs_URL = 'http://store.steampowered.com/api/packagedetails/?packageids=' . $Game['steam_appid'] .
'&cc=' . $cc . '&filters=basic,price_overview';
if ($JSON = file_get_contents($Subs_URL))
{
$DecodedJson = json_decode($JSON,true);
foreach($Chunks as $Chunk)
{
if (!isset($DecodedJson[$Chunk['steam_appid']]['data']['steam_appid']))
{
$DecodedJson[$Chunk['steam_appid']]['data']['steam_appid'] = $Chunk['steam_appid'];
}
}
//echo '<pre>';
//print_r($DecodedJson);
//print_r(array_keys($DecodedJson));
$GameList = array_merge($GameList,$DecodedJson);
}
else
{
die("Steam API timed out!");
}
}
Here's an example of what $Chunks is:
array(1358) {
[0]=>
array(4) {
["steam_appid"]=>
string(6) "227580"
["name"]=>
string(10) "10,000,000"
["dlc"]=>
string(1) "0"
["bundle"]=>
string(1) "0"
}
[1]=>
array(4) {
["steam_appid"]=>
string(6) "206712"
["name"]=>
string(21) "Cities in Motion: Ulm"
["dlc"]=>
string(1) "1"
["bundle"]=>
string(1) "0"
}
[2]=>
array(4) {
["steam_appid"]=>
string(6) "259620"
["name"]=>
string(24) "3079 -- Block Action RPG"
["dlc"]=>
string(1) "0"
["bundle"]=>
string(1) "0"
}

Categories