use persistent connection to grab data - php

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"
}

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.

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";
}

Query gives one indexed array with many elements

I have code like this:
$ch = #new mysqli ($config['db']['host'],$config['db']['user'],$config['db']['password'],$config['db']['database']);
if($result = $ch->query("SELECT pid FROM posts"))
{
while($pids = $result->fetch_assoc())
{
var_dump($pids);
}
var_dump gives me:
array(1) { ["pid"]=> string(1) "1" } array(1) { ["pid"]=> string(1) "2" } array(1) { ["pid"]=> string(1) "3" } array(1) { ["pid"]=> string(1) "4" }
I have two problems:
In database column 'pid' is an int type but the query yields an array of strings
All records from database (4) are saved in one row in an array (got only one index)
Because of that I can't use max(), because it gives me all records (4321).
You have got 4. Check correctly. The var_dump() executes four times, returning a single array (column - row values):
array(1) {
["pid"]=> string(1) "1"
}
array(1) {
["pid"]=> string(1) "2"
}
array(1) {
["pid"]=> string(1) "3"
}
array(1) {
["pid"]=> string(1) "4"
}
If you want everything to be in a single variable, use:
$allPids = array();
while (false != ($pids = $result->fetch_assoc())) {
$allPids[] = $pids;
}
var_dump($allPids);
You need to store them in one array first.
while($pids = $result->fetch_assoc())
{
$array[] = $pids;
}
var_dump($array);
And for the data type PHP will cast them accordingly.

$_POST values changing or disappearing inside foreach loop

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.

create ul and li using a multidimensional array in php

I have the following array:
$tree_array
When I do a var_dump, I get:
array(6) {
[0]=> string(23) "$100,000 Cash Flow 2013"
[1]=> array(6) {
[0]=> string(1) "2" ["Goal_ID"]=> string(1) "2"
[1]=> string(13) "Sell Iron Oak" ["Opportunity"]=> string(13) "Sell Iron Oak"
[2]=> string(2) "10" ["OID"]=> string(2) "10"
}
[2]=> array(2) {
[0]=> string(32) "ask her if she would like to buy" ["Activity"]=> string(32) "ask her if she would like to buy"
}
[3]=> array(6) {
[0]=> string(1) "2" ["Goal_ID"]=> string(1) "2"
[1]=> string(8) "Sell Car" ["Opportunity"]=> string(8) "Sell Car"
[2]=> string(2) "11" ["OID"]=> string(2) "11"
}
[4]=> array(2) {
[0]=> string(52) "Call Roy back to see if he would like to purchase it" ["Activity"]=> string(52) "Call Roy back to see if he would like to purchase it"
}
[5]=> array(1) {
["tot_opp"]=> NULL
}
}
My end goal is to create unordered lists and lists (ul, li) with this data. There will be more data added to the array as the database gets updated, so it will keep growing. My goal is to loop through the array and have it create the following code and be able to keep creating lists as the data grows. I am new to php and not sure how to accomplish this.
<ul>
<li>$100,000 Cash Flow 2013</li>
<ul>
<li>Sell Iron Oak</li>
<ul>
<li>ask her if she would like to buy</li>
</ul>
<ul>
<li>Sell Car</li>
</ul>etc...
Any help will be greatly appreciated! Thank you in advance!
You need a recursive function for that, not a loop. This way it will handle any depth of your source array.
function make_list($arr)
{
$return = '<ul>';
foreach ($arr as $item)
{
$return .= '<li>' . (is_array($item) ? make_list($item) : $item) . '</li>';
}
$return .= '</ul>';
return $return;
}
echo make_list($source_array);
Seems like a simple enough recursion to me:
function arrayToList($in) {
echo "<ul>";
foreach($in as $v) {
if( is_array($v)) arrayToList($v);
else echo '<li>' . $v . '</li>';
}
echo "</ul>";
}
It looks like you have some duplicate values up there. Are you using mysql_fetch_array? You should be using mysql_fetch_assoc or mysql_fetch_row depending on whether you need an associative or indexed array.

Categories