I've got the following sql query:
$sql = "SELECT lat, lang
FROM users";
I then use the following code to put the results of the array into two arrays, one for lat and one for lang.
$i = 0;
foreach($results as $row) {
$latArray = array();
$langArray = array();
$latArray[$i] = $row['lat'];
$langArray[$i] = $row['lang'];
$i = ($i + 1);
}
However, it seems that only the last value that is passed to the array is stored. When I echo out each value of the array I get the following error: Undefined offset: 0 which I believe means theres nothing at latArray[0].
I'm sure I've missed something obvious here but why aren't all the values copied to the new array?
$i = 0;
$latArray = array(); //Declare once, do not redeclare in the loop
$langArray = array();
foreach($results as $row) {
$latArray[$i] = $row['lat'];
$langArray[$i] = $row['lang'];
$i = ($i + 1);
}
Declare your array before the loop
$latArray = array();
$langArray = array();
foreach($results as $row) {
$latArray[$i] = $row['lat'];
$langArray[$i] = $row['lang'];
$i = ($i + 1);
}
You should put
$latArray = array();
$langArray = array();
Before foreach cycle (like you do with your counter $i), 'cause with every new value from $result it resets thous values..
so your code will look like:
$i = 0;
$latArray = array();
$langArray = array();
foreach($results as $row) {
$latArray[$i] = $row['lat'];
$langArray[$i] = $row['lang'];
$i = ($i + 1);
}
use fetch_assoc instead:
$latArray = array();
$langArray = array();
while($row = mysql_fetch_assoc($your_query)){
$latArray[$i] = $row['lat'];
$langArray[$i] = $row['lang'];
$i++;
}
if u are using msqli us mysqli_fetch_assoc
Related
I need to store service_ids and country_ids in an array in this format
array
[0]["service_id"] should give service id at 0th
index
array[0]["country_id"] should give me country id at 0th index and so on.
function service_ids($conn) {
$ids = array();
$sql = "SELECT id from services";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
array_push($ids, $row["id"]);
}
return $ids;
}
$service_ids = service_ids($conn);
function country_ids($conn) {
$ids = array();
$sql = "SELECT id FROM countries";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
array_push($ids, $row["id"]);
}
return $ids;
}
$country_ids = country_ids($conn);
`//I am having problem here how to store it.
$z = array();
for ($i=0; $i < count($service_ids); $i++) {
$z = array(`
array("service_id"=>$service_ids[$i], "country_id"=>$country_ids[$i])
);
}
print_r($z);
?>
You are basically overwriting array in each iteration in final loop, instead of that store new array in new array index
$z = array();
$counter = 0;
for ($i=0; $i < count($service_ids); $i++) {
$counter = count($z);
$z[$counter]["service_id"] = $service_ids[$i];
$z[$counter]["country_id"] = $country_ids[$i];
}
Hey I made an API in PHP from my MySQL database, It is rather CPU intensive and is being called multiple times a second.
$timer = $candle_time * 60;
$DATABASE_HOST = '';
$DATABASE_USER = '';
$DATABASE_PASS = '';
$DATABASE_NAME = '';
$response = array();
$link = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
$query = "SELECT * FROM table WHERE name LIKE 'name' ORDER BY table.datetime ASC";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
$dates .= $row[1]. ',';
$price .= $row[2]. ",";
$datetime .= $row[3]. ',';
}
$dates = explode(",",$dates);
$price = explode(",",$price);
$datetime = explode(",",$datetime);
for($i = 0; $i < count($dates); $i++){
array_push($response,array(strtotime($datetime[$i]),$dates[$i],$price[$i]));
}
$counting_segments = 0;
$grouped_prices = array();
$final_grouping = array();
$rounded = ceil($response[0][0]/$timer)*$timer;
$counted = count($response)-1;
for($i = 0; $i < count($response); $i++){
if($i == $counted){
$rounded = ceil($previous_time/$timer)*$timer;
array_push($final_grouping,array($rounded,$grouped_prices));
}
if($response[$i][0] > $rounded){
$previous_time = $response[$i][0];
array_push($final_grouping,array($rounded,$grouped_prices));
$grouped_prices = array();
$rounded = ceil($response[$i][0]/$timer)*$timer;
}
if($response[$i][0] < $rounded){
$previous_time = $response[$i][0];
array_push($grouped_prices,$response[$i][2]);
} else {
array_push($grouped_prices,$response[$i][2]);
}
}
$new_array = array();
for($i = 0; $i < count($final_grouping); $i++){
$first_array = $final_grouping[$i][0];
$second_array = $final_grouping[$i][1];
$first_price = $second_array[0];
$last_price = end($second_array);
$high_price = max($second_array);
$low_price = min($second_array);
$final_date = $first_array;
$obj = new StdClass;
$obj->time = $final_date;
$obj->open = $first_price;
$obj->high = $high_price;
$obj->low = $low_price;
$obj->close = $last_price;
array_push($new_array,$obj);
}
$json_api = json_encode($new_array);
echo $json_api
I think the reason for the 503 is the CPU power it is taking to calculate the requests. Is there a way I can have a script or something that pulls the data and saves it to a php file every second to lessen the load or is there a better way of doing this?
I did run this personally and it works perfectly, however with more people requesting from it it provides a 503 often.
Thanks.
The PHP code itself doesn't look like it should overload the CPU. However, there are a lot of things you can do to optimize it
How's the query performing. Execute the query directly and see if you need to add an index. This could be an index on 2 fields: name and datetime.
You're using specific columns date, price, and datetime, but you're getting all rows in the response. It's better to specify the columns you want
SELECT `date`, `price`, `datetime` FROM table WHERE name LIKE 'name' ORDER BY table.datetime ASC
You're building up comma-separated strings and then splitting them right after. That's unnecessary. Instead build-up arrays.
while ($row = mysqli_fetch_row($result)) {
$dates[] = $row[1];
$price[] = $row[2];
$datetime[] = $row[3];
}
In this case, you don't even need separate arrays, but can just build-up $response in the fetch loop.
while ($row = mysqli_fetch_row($result)) {
$response[] = array(strtotime($row[1]), $row[2], $row[3]);
}
P.S. Don't use array_push() unless you care about the inserted index. The $array[] = $value syntax is faster.
Just count once, not every iteration in the loop
$counted = count($response);
for($i = 0; $i < $counted; $i++){
if($i == $counted - 1){
I have set up an array called $compData by importing data from MySql and pushing two separate arrays called $yearsArray and $salesArray into $compData. Before pushing these two arrays to $compData I have first set their ['name'] to 'Year' and 'Sales', respectively. The code for this is included below.
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = 'ID_YEAR'");
$yearsArray = array();
$yearsArray['name'] = 'Year';
while($r = mysqli_fetch_array($sth)) {
For ($n = 1; $n <= $CI_YEARS; $n++){
$yearsArray['data'][] = $r["Year$n"];
}
}
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = 'IS_SALES'");
$salesArray = array();
$salesArray['name'] = 'Sales';
while($rr = mysqli_fetch_assoc($sth)) {
For ($n = 1; $n <= $CI_YEARS; $n++){
$salesArray['data'][] = $rr["Year$n"];
}
}
$compData = array();
array_push($compData,$yearsArray); // 0
array_push($compData,$salesArray); // 1
Now I want to access and echo the data in $compData by using the code below, but this doesn't work. I am not very comfortable with PHP and am wondering if I am not using the ['Year'] and ['Sales'] identifiers correctly. Any help is much appreciated.
foreach($compData['Year'] as $result) {
echo $result, '<br>';
}
foreach($compData['Sales'] as $result) {
echo $result, '<br>';
}
You've set 'Year' as the value of key 'name', but try to use it as key (of another array).
Now you have
echo $compData[0]['name']; // -> 'Year'
echo $compData[1]['name']; // -> 'Sales'
You probably want
$compData = array();
$compData['Year'] = $yearsArray;
$compData['Sales'] = $salesArray;
instead of the array_push..
I have a query like this:
select truck, oil_type, km_min, km_max from trucks;
I'm using codeigniter and with the $query->result_array() function so its loaded in an associative array with this structure:
/*
array(
truck
oil_type
km_min
km_max
)
*/
$arr[0]["truck"] = 2;
$arr[0]["oil_type"] = 2;
$arr[0]["km_min"] = 345;
$arr[0]["km_max"] = 567;
$arr[1]["truck"] = 2;
$arr[1]["oil_type"] = 4;
$arr[1]["km_min"] = 234;
$arr[1]["km_max"] = 867;
$arr[2]["truck"] = 1;
$arr[2]["oil_type"] = 2;
$arr[2]["km_min"] = 545;
$arr[2]["km_max"] = 867;
$arr[3]["truck"] = 4;
$arr[3]["oil_type"] = 3;
$arr[3]["km_min"] = 45;
$arr[3]["km_max"] = 567;
Then, I'm trying to restructure it grouping the trucks by the id, something like this:
/*
trucks - array(
truck
truck_data - array(
oil_type
km_min
km_max
)
)
*/
$arr["truck"][0]= 2;
$arr["truck"][0]["truck_data"][0]["oil_type"] = 2;
$arr["truck"][0]["truck_data"][0]["km_min"] = 345;
$arr["truck"][0]["truck_data"][0]["km_max"] = 567;
$arr["truck"][0]["truck_data"][1]["oil_type"] = 4;
$arr["truck"][0]["truck_data"][1]["km_min"] = 234;
$arr["truck"][0]["truck_data"][1]["km_max"] = 867;
$arr["truck"][1]= 1;
$arr["truck"][1]["truck_data"][0]["oil_type"] = 2;
$arr["truck"][1]["truck_data"][0]["km_min"] = 545;
$arr["truck"][1]["truck_data"][0]["km_max"] = 867;
$arr["truck"][2]= 4;
$arr["truck"][2]["truck_data"][0]["oil_type"] = 3;
$arr["truck"][2]["truck_data"][0]["km_min"] = 45;
$arr["truck"][2]["truck_data"][0]["km_max"] = 567;
I thought in something like the code below:
$res = $query->result_array();
$cnt_total = count($res);
$y = 0;
for ($x=0; $x < $cnt_total -1 ; $x++) {
$truck = $res[$x]["truck"];
$trucks["truck"][$y] = $truck;
$q = $x + 1;
$i = 0;
do{
$trucks[$y][$i]["oil_type"] = $res[$q]["oil_type"];
$trucks[$y][$i]["km_min"] = $res[$q]["km_max"];
$trucks[$y][$i]["km_max"] = $res[$q]["km_max"];
$q++;
$i++;
if ($q <= $cnt_total) break;
} while ( $truck === $res["truck"][$q] );
$y++;
}
But does not work properly... I'm too far of the solution? The performance It's important for me in this particular case.
There is a phpfiddle where you can try:
http://phpfiddle.org/main/code/67j-ui5
Any idea, tip, or advice will be appreciated, and if you need more info, let me know and I'll edit the post.
Try this:
$res = $query->result_array();
$trucks = array();
foreach ($res as $row) {
$truck["truck"] = $row["truck"];
$truck["truck_data"] = array(
'oil_type' => $row["oil_type"],
'km_min' => $row["km_min"],
'km_max' => $row["km_max"],
);
$trucks[] = $truck;
}
var_dump($trucks);
What you've provided as a desired result is a little ambiguous. This might give what you're asking for.
$trucks=array();
$res = $query->result_array(); // assuming this is actually several trucks
foreach ($res as $r){
// set up the array from the data without writing out every column manually
$truck=array(
'truck'=>$r['truck'],
'truck_data'=>$r,
);
// remove the bit you wanted separately as 'truck' from 'truck_data'
unset($truck['truck_data']['truck']);
// push into $trucks
$trucks[]=$truck;
}
Is this what you need? conversion result is stored in $result
$result = array();
foreach($query->result_array() as $truck)
{
$new_truck = array();
$new_truck['truck'] = $truck['truck'];
$new_truck['truck_data'] = array();
$new_truck['truck_data']['oil_type'] = $truck['oil_type'];
$new_truck['truck_data']['km_min'] = $truck['km_min'];
$new_truck['truck_data']['km_max'] = $truck['km_max'];
array_push($result, $new_truck);
}
I have the following code which is meant to cycle through names submitted on a form:
$row_count = count($_POST['name']);
if ($row_count > 0) {
mysql_select_db($database, $connection);
$name = array();
$workshop = array();
for($i = 0; $i < $row_count; $i++) {
// variable sanitation...
$name[i] = mysql_real_escape_string(ucwords($_POST['name'][$i]));
$workshop[i] = mysql_real_escape_string($_POST['workshop'][$i]);
}
$names = "('".implode("','",$name)."')";
.....etc
For some reason $names is only returning the last name submitted on the form, rather than all of the names. Could someone help me get this working correctly?
Thanks,
Nick
problem is here
$name[i] =
$workshop[i] =
solution:
$name[$i] =
$workshop[$i] =
now your code is working in this way:
$name["i"] =
$workshop["i"] =
so you have only one element in $name, $workshop arrays. (last from loop)