I've looked on stackoverflow for the answer, but no one explains it properly.
I have a while loop that works:
info = array();
while($get_info= mysql_fetch_array($info_result)){
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
And when I print out the array:
Array ( [team_id] => 26 [team_points] => 100 )
But my foreach returns an invalid argument.
foreach ($info as $info_mation ){
echo $info_mation['team_id'];
echo $info_mation['team_points'];
echo "<br/>";
}
I've tried many different ways but nothing works.
Thanks!
Problem is in fetching data from DB. Modify your while loop like this:
info = array();
while($get_info = mysql_fetch_array($info_result)){
$temp_info = array();
$temp_info['team_id'] = $get_info['team_id'];
$temp_info['team_points'] = $get_info['team_points'];
$info[] = $temp_info;
}
Now your foreach loop should work properly.
Here is a bit more explanation, if what you've seen so far doesn't make sense. When you do this:
$info = array();
while($get_info = mysql_fetch_array($info_result)) {
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
You are overwriting $info with each iteration of the while loop. So at the end of your loop, $info will only contain the last row of your query result.
This explains the result you see:
Array ( [team_id] => 26 [team_points] => 100 )
So when you iterate this array with
foreach ($info as $info_mation ){
echo $info_mation['team_id'];
echo $info_mation['team_points'];
echo "<br/>";
}
$info_mation will contain 26, and then 100, which are indeed invalid for foreach.
You need to create a multidimensional array rather than a one-dimensional array. You can do that by modifying your while loop slightly:
while($get_info= mysql_fetch_array($info_result)) {
$info[] = $get_info;
}
Doing it this way adds a new array element to the $info array with each iteration, rather than overwriting the same two elements repeatedly.
this is your code:
info = array();
while($get_info= mysql_fetch_array($info_result)){
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
change it to this:
$info = array();
while($get_info= mysql_fetch_array($info_result)){
$info[] = array(
'team_id' => $get_info['team_id'],
'team_points' => $get_info['team_points']
);
}
so, your $info variable contains all the array from the sql result you made.
foreach($info as $inf) {
echo $inf['team_id'];
echo $inf['team_points'];
echo '<br>';
}
and we're done! :)
Related
I have php result set, and from these result i am extracting value using php foreach loop. I put the foreach loop value in array $summery[]. but when i try to print value its print value at once. but i need separate value/result set for each foreach loop as json code so that i can print each result separately. My foreach loop following :
foreach($result_UserWrSet as $UserWrInfo) {
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
}
print json_encode($summery);
My result become
["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done","01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]
but i need :
[["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done"],["01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]]
Use this code, you need to use another array in which all the sub array's to be pushed and encode that array after pushing all the items into it
<?php
$dataArray = array(); /// empty array in which sub array's to be pushed..
foreach($result_UserWrSet as $UserWrInfo) {
$summery= array();
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
////Push sub array i.e summary into the main array...
$dataArray[] = $summery;
}
print json_encode($dataArray);
?>
You need a multidimensional array, you can follow below code:
$result_UserWrSet = array(
'0' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'),
'1' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'));
foreach($result_UserWrSet as $key => $UserWrInfo) {
$summery[$key][]=$UserWrInfo['wr_id'];
$summery[$key][]=$UserWrInfo['wr_number'];
$summery[$key][]=$UserWrInfo['wr_title'];
}
print json_encode($summery);
output: [["12","785","title1"],["12","785","title1"]]
Good Luck :)
Currently, you are just adding new items to a one dimensional array. You need to create a separate array per result, like this:
foreach($result_UserWrSet as $UserWrInfo) {
$item = array();
// Change all $summary in the loop to: $item, like this:
$item[]=$UserWrInfo['wr_id'];
$item[]=$UserWrInfo['wr_number'];
$item[]=$UserWrInfo['wr_title'];
//...and so on
// Then add this last in your loop:
$summary[] = $item;
}
This will create one array per iteration that is put in the main array, which then becomes a multi dimensional array.
This might seem like a really easy question but it has got me stumped lol. I am trying to print the rows received from the database. I want to store the rows inside an array and then print them using a for loop. I know that the query works however when I try to print the array elements it only prints the word array. I have tired doing it with a foreach loop and a simple for loop. If anyone can point me in the right direction would be a life saver.
Printing Php Code
<?php
$type = "FREE";
$free = getTerms($type);
echo "<p>";
for($j = 0; $j < count($free); $j++)
{
echo "start".$free[$j]."end";
}
echo "</p>";
?>
geting the rows from the database
function getTerms($type)
{
$terms = array();
$connection = mysql_open();
$query = "select terms from terms_and_con where accountType='$type' && currentTerms='YES'";
$results = mysql_query($query, $connection) or show_error("signUp.php", "", "");
while($row = mysql_fetch_array($results))
{
$terms[] = $row;
}
mysql_close($connection) or show_error("signUp.php", "", "");
return $terms;
}
Each entry in the $free array is itself an array (from $row).
Try
echo 'start', $free[$j]['terms'], 'end';
Alternatively, you may find a foreach loop more semantically appropriate
foreach ($free as $row) {
echo 'start', $row['terms'], 'end';
}
Edit: I'd advise using mysql_fetch_assoc() instead of mysql_fetch_array() if you're only going to use associative entries from $row.
the thing is function mysql_fetch_array ( as the name suggests) returns an ( in your case both associative and number) array. so $row is actually array(0 => VALUE, 'terms' => 'VALUE')
So what you are trying to echo is actually an array.
Simple fix:
replace:
$terms[] = $row;
with:
$terms[] = $row[0];
How can I add key value pairs to an array?
This won't work:
public function getCategorieenAsArray(){
$catList = array();
$query = "SELECT DISTINCT datasource_id, title FROM table";
if ($rs=C_DB::fetchRecordset($query)) {
while ($row=C_DB::fetchRow($rs)) {
if(!empty($row["title"])){
array_push($catList, $row["datasource_id"] ."=>". $row["title"] );
}
}
}
return($catList);
}
Because it gives me:
Array ( [0] => 1=>Categorie 1 [1] => 5=>Categorie 2 [2] => 2=>Caterorie 2 )
And I expect:
Array ( [1] =>Categorie 1 [5] => Categorie 2 )
$data =array();
$data['user_code'] = 'JOY' ;
$data['user_name'] = 'JOY' ;
$data['user_email'] = 'joy#cargomar.org';
Use the square bracket syntax:
if (!empty($row["title"])) {
$catList[$row["datasource_id"]] = $row["title"];
}
$row["datasource_id"] is the key for where the value of $row["title"] is stored in.
My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:
$catList[$row["datasource_id"]] = $row["title"];
In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.
You can create the single value array key-value as
$new_row = array($row["datasource_id"]=>$row["title"]);
inside while loop, and then use array_merge function in loop to combine the each new $new_row array.
You can use this function in your application to add keys to indexed array.
public static function convertIndexedArrayToAssociative($indexedArr, $keys)
{
$resArr = array();
foreach ($indexedArr as $item)
{
$tmpArr = array();
foreach ($item as $key=>$value)
{
$tmpArr[$keys[$key]] = $value;
}
$resArr[] = $tmpArr;
}
return $resArr;
}
No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me
class line_details {
var $commission_one=array();
foreach($_SESSION['commission'] as $key=>$data){
$row= explode('-', $key);
$this->commission_one[$row['0']]= $row['1'];
}
}
I am pretty new to php and could sure use some help understanding how to get my result the way I need it from a database query.
What I need is an associative array like this, 'bla'=>'bla'. What I am getting from my foreach loop is this from a print:
[0] => Array
(
[0] => test0
[name] => test0
[1] => 1
[customer_id] => 1
)
[1] => Array
(
[0] => test
[name] => test
[1] => 2
[customer_id] => 2
)
Here is my loop:
foreach($res as $key=>$val)
{
// have no idea..
}
Can someone please help me to format my results so that they are like 'index'=>'value'
Thanks for any help.
Here is a sample code that uses a foreach but yet pulls an association. I don't get it. I am thinking that my result set with the indexes are because I am not writing the loop correctly. Here is the code that uses the foreach
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
Here is the part of the database class that I am using to fetch the results.
$returnArray = array();
$i=0;
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
if($row)
$returnArray[$i++] = $row;
}
mysql_free_result($result);
return $returnArray;
After using the code that was given to me to omit the index numbers, here is what I am now left with. Its close but not what I need.
Array
(
[id] => 1
[cust] => bobs auto
)
This is what the above line should read like
'1' => 'bobs auto'
What I am trying to do is to format the output for a JSON call for a suggestion box.
I cannot get this to work. Here is everything after my db connection.
$out_array = array();
foreach($items as $key=>$val)
{
if(is_int($key))
{
continue;
}
$out[$key['id']] = $val['cust'];
}
//echo'<pre>';
//print_r($out_array);
//echo'</pre>';
foreach ($out_array as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
OK, I think I am coming down to the home stretch. I have what I need sort of. This is the code I have so far.
$out_array = array();
foreach($items as $key)
{
$out_array[$key] = $val;
//$out_array[$key['id']] = $key['cust'];
}
Notice that the commented line does not work, It outputs like the id twice but the line that isn't commented out works just fine. Here is the output from that.
Array
(
[8] =>
[FAT BURGER] =>
)
From this point, would I just use another foreach to iterate over the entire set of data? The array output you see above is from a print_r.
This is what I now have and it returns the correct association however, I must comment out the strpos condition to get any results back and I don't know why. Am I correct in nesting these foreach loops like I have?
$out_array = array();
foreach($items as $key)
{
// $out_array[$key] = $val;
$out_array[$key['id']] = $key['cust'];
foreach ($out_array as $key=>$value)
{
if (strpos(strtolower($key), $q) !== false)
{
echo "$key|$value\n";
}
}
}
So you don't want the numeric indexes in your array? You must be using mysql_fetch_array(), which returns your results with both numeric and string keys. Use mysql_fetch_assoc() to get an array with only the string keys (the string being the column name).
Try something like this. It works by skipping the integer indices, and putting the non-integer indices into an output array.
$out_array = array();
foreach($res as $key=>$val) {
if(is_int($key)) {continue;}
$out_array[$key] = $val;
}
EDIT:
$out_array = array();
foreach($items as $key=>$val)
{
if(is_int($key))
{
continue;
}
}
$out[$out_array['id']] = $out_array['cust'];
//echo'<pre>';
//print_r($out_array);
//echo'</pre>';
foreach ($out as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}
}
Assuming this is a MySQL database, the results, if more than one, are returned as a multidimensional array.
When you run the query:
$query = "SELECT * FROM Table WHERE ...";
$query = mysql_query($query);
while($info = mysql_fetch_assoc($query)){
//$info is now a single row, associative array
echo print_r($info);
}
the echo print_r displays the results the way you are looking for them now 'index'=>'value'
EDIT: based on comments.
If you absolutely CAN'T get rid of the mysql_fetch_array then you'll have to hack the code. It's not clean and I strongly advise refactoring but below is the code you'll need to create an array of field name indexes only from what you're given
$my_array = array();
$info = $data[0]; //grab the first row of your data set from the original question.
foreach($info as $index => $value){
if(!is_int($index)){
$my_array[$index] = $value;
}
}
The newly created $my_array will be in the format you're looking for.
You got this array from a query and result function from PHP, yeah?
If you were using mysql, it's actually easier to do it like below.
$query = mysql_query("SELECT * FROM dbname"); //Create the query to your database
while($data = mysql_fetch_array($query)) //Loop through our results from the query
{
echo($data['fieldname']."<br/>"); //echo out data through the loop
}
$ret = array();
foreach($rows as $row)
{
$ret[$row['id']] = $row['cust'];
}
$json = json_encode($ret);
echo $json;
// Prints something like:
//
// {1:'bob'}
Note the use of json_encode.
Ok, regarding my last question. I was incorrect in nesting the foreach loops. I also had a typo in my code. It is working, finally. Thank you to all that have helped me!
In a while loop I have:
$row = mysql_fetch_array($result)
Held under $row are two arrays which when shown using print_r display the following:
Array
(
[4] => Post Content
[value] => Post Content
)
Array
(
[4] => Post Title
[value] => Post Title
)
How can I choose "Post Content" and "Post Title" from the array without it being repeated in the while loop?
The original version of this question confused the duplication with the problem. The issue is how to extract the second array [value] when they are both held under $row.
You can also make sure the values won't be insterted twice using mysql_fetch_assoc() or mysql_fetch_row().
Thus:
$row = mysql_fetch_assoc($result);
Array
(
['value'] => Post Content
)
Array
(
['value'] => Post Title
)
You want to make sure an array only has unique values? If that doesn't work with the arrays in an array, it's classic de-duping with a store of what you've already seen.
$dedupedValues = array()
foreach ($row as $items) {
if (! is_set($dedupedValues[$items['value']])) {
$dedupedValues[$items['value']] = true; // we have this value
echo "echo the title/value....";
}
}
Another alternative is to improve the SQL that gets the data to begin with to avoid duplicates in the first place (see: MySQL 'DISTINCT')
Pim Jager showed much better way of doing this, but if you insist on using mysql_fetch_array():
$i = 0;
$size = count($row);
if ($size > 0) {
while ($i < floor($size / 2)) {
..... = $row[$i];
$i += 1;
}
}
Edit:
After reading again, I'm not sure if I quite understand the question.
If you have nested arrays for example:
$row = array('data1' => array('orange', 'banana', 'apple'),
'data2' => array('carrot', 'collard', 'pea'));
And you want to access each array then:
$data1 = $row['data1'];
// = array('orange', 'banana', 'apple')
$data2 = $row['data2'];
// = array('carrot', 'collard', 'pea')
// OR
$orange = $row['data1'][0];
$banana = $row['data1'][1];
$apple = $row['data1'][2];
$carrot = $row['data2'][0];
// ... so on..
Taking that in account the loop looks like this:
$i = 0;
$size = count($row);
if ($size > 0) {
while ($i < floor($size / 2)) {
$something = $row['data1'][$i]; //Or $row[0][$i]; using your example
$something = $row['data2'][$i]; //Or $row[1][$i]; using your example
$i += 1;
}
}
But I really suggest using mysql_fetch_assoc() and foreach loop, like in Pims Jagers example
Final solution was found by slightly restructuring the original query as per Topbit's suggestion and the use of two while loops.
while($row_title = mysql_fetch_array($result_title)){
$row_body = mysql_fetch_array($result_body);
// code
}
Thank you to all those who suggested solutions.