Returning values from an array - php

Is there any reason why this code would avoid the first value in an array?
$rappels = array();
$i = 0;
while($row = $result->fetch_assoc()) {
foreach($row as $key=>$val) {
$rappels[$i][$key] = $val;
}
$i++;
}
return $rappels;
When I return the rappels, it always seems to avoid returning the very first item, which should be [0] in the array.

You have a number of redundancies in your code. You don't need $i nor do you need the foreach loop.
$rappels = array();
while($row = $result->fetch_assoc()) {
$rappels[] = $row;
}
return $rappels;
Your code as you posted it shouldn't remove any rows. You may need to look at the code you haven't posted to see if there's something there that's skipping the first row.

Related

Expand (json) object in php

I want this sql-query result (from a log file, i hope it's accurate)
[
{"id":"1","text":"123"}
,{"id":"2","text":"456"}
] []
to become this
{
1: {"id":"1","text":"123"}
,2: {"id":"2","text":"456"}
}
I tried array_push and array_combine but am new to PHP and was unsuccessful so far.
Short: I want to add keys (starting with 1) to an array of objects.
One attempt
$i = 1;
while ($row = fetchRow($result)) {
array_push($arr_result, $row);
array_push($i, $arr_result);
$i++;
}
But $arr_result looks like the first code sample.
You dont need $i using $arr_result[] will create a new occurance in your array.
while ($row = fetchRow($result)) {
// this forces the array to start at 1 instead of 0 if thats what you really want
if (count($arr_result) == 0){
$arr_result[1] = $row;
} else {
$arr_result[] = $row;
}
}
Or if the key is supposed to be the id from the row
while ($row = fetchRow($result)) {
$arr_result[$row['id']] = $row;
}

how to loop through array with dynamic keys in PHP

I have an array data where I am storing the result of an SQL query as below :
$stmt = sqlsrv_query($db,$sql);
$data = [];
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
if(!empty($row)) { $data[] = $row; } }
then I want to create a group key which is the concatenation of specific keys of my array data as below :
foreach ($data as $d) {
$group_key = $d['id'].'_'.$d['Country'].'_'.$d['Order Numer'];
//rest of my code
}
it works fine but I want to choose the keys dynamically instead of setting up manually id, Country and Order Number...
let's say I have an array $PostKeys = ["id","Country","Order Number"]; this array will vary depending on the values selected by user...
What I did is :
$PostKeys = ["id","Country","Order Number"];
foreach ($data as $d) {
foreach($PostKeys as $value)
{ $array_group_key[] = $d[$value] ; }
$group_key = implode("_",$array_group_key);
// rest of my code
}
I am supposed to get the same result but there is always mismatch. I didn't figure out where is the issue exactly. Any suggestions please ? Thank you very much.
You need to empty $array_group_key each time through the loop. Otherwise, you're appending to the results from all the previous rows.
foreach ($data as $d) {
$array_group_key = [];
foreach($PostKeys as $value)
{
$array_group_key[] = $d[$value] ;
}
}

Making an Array from Database MySQL

I have database connection. I want to make an array but something is problem i think. Here is my array code:
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
foreach ($result as $row) {$data[] = $row;}
print_r($data);
$no=1;$total_deger=count($data);
echo $total_deger;
for($i=0;$i<$total_deger);$i++){
$xxx[i]="[Date.UTC(".$data[i]['year'].",".$data[i]['month'].",".$data[i]['day'].",".$data[i]['saat'].",".$data[i]['dakika'].",00),".$data[i]['Guc']."]";if($no < $total_deger){echo ",";}
echo $xxx[i];
}
When I run this code, nothing happens in page. When I write to for example 0 for i. I can see my array value. Where do I mistake?
Code with correction and suggestion (both are commented):-
<?php
error_reporting(E_ALL); // check all errors
ini_set('display_errors',1);// display those errors
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
if ($result->num_rows > 0) { // check you got results or not
while($row = $result->fetch_assoc()) {
$data[] = $row; // assign them
}
}
//foreach ($result as $row) {$data[] = $row;} // not needed
print_r($data);
$no=1;
$total_deger= count($data);
echo $total_deger;
for($i=0;$i<$total_deger;$i++){ // remove )
$xxx[$i]="[Date.UTC(".$data[$i]['year'].",".$data[$i]['month'].",".$data[$i]['day'].",".$data[$i]['saat'].",".$data[$i]['dakika'].",00),".$data[$i]['Guc']."]"; // use $i instead of i
if($no < $total_deger)
{
echo ",";
}
echo $xxx[$i];
}
Note:- Always add some error reporting code. So that all errors will populated and you can rectify those
Also better would be to use foreach() instead of for loop (as it will take care of indexes itself):-
//use foreach
foreach ($data as $dat){
echo "[Date.UTC(".$data['year'].",".$data['month'].",".$data['day'].",".$data['saat'].",".$data['dakika'].",00),".$data['Guc']."]";
}
Firstly you want to check your SQL query returns rows. Then I think you need to modify your foreach to a while as below. Also checking that rows are returned before looping.
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
As per example given here: http://www.w3schools.com/php/php_mysql_select.asp

Echo values of arrays?

I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}

What is the problem with this foreach loop?

why doesnt this array work? What do I do wrong? The result of my foreach loop is always either empty or just some weird numbers and signs. So what is wrong with my foreach loop?
$array = array();
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array["some"] = $row["some"];
$array["some2"] = $row["some2"];
}
}
foreach($array as $property=>$value) {
echo '<p>'.$value["some"].' - '.$value["some2"].'</p>'; }
$array will have only two properties, some and some2. Therefore your foreach loop doesn't make any sense. The foreach will loop two times, the first time with this:
$property = 'some';
$value = $row["some"];
and the second with this:
$property = 'some2';
$value = $row["some2"];
You will have to make $array multidimensional in your first loop by doing this:
while($row = mysqli_fetch_array($result)) {
$new = array();
if(!empty($row["some"])) {
$new["some"] = $row["some"];
$new["some2"] = $row["some2"];
$array[] = $new;
}
}
or shorter:
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array[] = array('some' => $row["some"],
'some2' => $row["some2"]);
}
}
$array["some"] and $array["some2"] are specific array elements. You are overwriting them every iteration of your while loop.
Not sure what you're trying to actually accomplish but I think possibly this is what you want:
$array = array();
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array["some"][] = $row["some"];
$array["some2"][] = $row["some2"];
}
}
foreach($array["some"] as $property=>$value) {
echo '<p>'.$value.' - '.$array["some2"][$property].'</p>';
}
or
$array = array();
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array[] = array('some' => $row["some"],
'some2' => $row["some2"]);
}
}
foreach($array as $property=>$value) {
echo '<p>'.$value['some'].' - '.$value['some2'].'</p>';
}
or similar...kinda depends on what you're ultimately trying to accomplish...
This doesn't explain the weird numbers and signs, but you are overwriting $array['some'] and $array['some2'] on each loop iteration.
Instead, try this:
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array[] = array("some"=>$row['some'], "some2"=>$row['some2']);
}
}
$array[] = array('some' => $row["some"], 'some2' => $row["some2"]);
But it would be better to retrieve only these columns.
Emil has the right answer :D. I love how people post so fast on here lol.

Categories