How to put value to blank array inside foreach loop php - php

I am using query in foreach loop (according to userType) and after query in foreach loop i am getting
following result
Array
(
[0] => Array
(
[bookingId] => 1
[userId] => 102
[status] => paid
}
[0] => Array
(
[bookingId] => 3
[userId] => 102
[status] => paid
}
[0] => Array
(
[bookingId] => 5
[userId] => 102
[status] => paid
}
...
}
Now i want all result outside foreach loop so i tried with following code but not working,showing me single record istead of multiple
I tried with following code but not working for me
$record=array();
foreach ($result as $key => $row)
{
$query= // mysql query
$rows = $query->result_array();
$record['bookingId']=$rows['0']['bookingId'];
$record['userId']=$rows['0']['userId'];
$record['status']=$rows['0']['status'];
}
echo "<pre>";print_R($record);

Don't you rewrite the value in the array every time?
$record = array();
foreach ($result as $key => $row) {
$query = // mysql query
$rows = $query->result_array();
$record[] = [
'bookingId' => $rows['0']['bookingId'],
'userId' => $rows['0']['userId'],
'status' => $rows['0']['status'],
];
}
echo "<pre>";
print_R($record);

You need to use it something like this.
$record = array();
foreach ($result as $key => $row)
{
$query = // mysql query
$rows = $query->result_array();
$record[]['bookingId'] = $rows['0']['bookingId'];
$record[]['userId'] = $rows['0']['userId'];
$record[]['status'] = $rows['0']['status'];
}
echo "<pre>";print_R($record);
Basically, you're missing updating the index of the array.

Related

Retrieving data from Multi dimensional Array in Codeigniter

I can't quite get my data from an array, it just shows a blank list of list items when I run my foreach loop.
When I print my array it outputs the following:
Array (
[Description] => Array (
[0] => sidewindo
[1] => sidewindo
[2] => sidewindo
[3] => testing )
[comments] => Array (
[0] => sidewindo
[1] => sidewindo
[2] => sidewindo
[3] => testing )
[Fld_id] => 625
[fld_IsPublic] => Array (
[0] => 1 )
[action] => s
[pk_id] => 7 )
My code so far
public function save_data($data)
{
foreach ($data as $row)
{
foreach ($row['Description'] as $show)
{
echo $show;
}
}
And i have tried the following kind of for loop also to retrieve data from the array. I am trying to retrieve data from the array and update it in another table in the database. This code I have written in my model before passing it to the view.
for($i=0;$i<count($comments);$i++)
{
$this->db->update->update('tblname',array('TK_id'=>$data['pk_id'],'Fld_id'=>$data['Fld_id'],'fld_description'=>$data['Description'],'fld_comments'=>$data['comments'],'fld_IsPublic'=>$data['fld_IsPublic']),array('TK_id'=>$data['pk_id'],'Fld_id'=>$data['Fld_id']));
}
}
First of all you should know that echo an array will produce a Notice ( Array to string conversion ), so depending in what environment you are working on you will prefer to use print_r.
Answering your question, before you echo, you should check if it's an array or not
public function save_data($data){
$update = array();
foreach ($data as $key=>$row){
if(is_array($row)){
foreach($row as $key2=>$row2){
$update[$key2] = $row2;
//echo $row2 . "<br>";
}
}else{
$update[$key] = $row;
//echo $row ."<br>";
}
}
}
And now you can use $update to update your table , include this on inside save_data() function, and if you needed, include save_data() inside a foreach. Remember that is recommended to use a where when updating data so:
//$this->db->where('id', $id);
$this->db->update('tblname', $update);
hope that helps
Change Your code from
public function save_data($data)
{
foreach ($data as $row)
{
foreach ($row['Description'] as $show)
{
echo $show;
}
}
to
public function save_data($data)
{
foreach ($data["comments"] as $key=>$row)
{
$data_update = array(
'TK_id' => $data['pk_id'],
'Fld_id' => $data['Fld_id'],
'fld_description' => $data['Description'][$key],
'fld_comments' => $row,
'fld_IsPublic' => $data['fld_IsPublic'][0]
);
$this->db->update('tblname',$data_update,array('TK_id'=>$data['pk_id'],'Fld_id'=>$data['Fld_id']));
//but this will update single row again and again
//my suggetion is use $this->db->insert('tblname',$data_update); instead
}
}
ANd you will be just fine

Merge two different array

I am confused with array.
What I want to do is two merge two array, but this kind of the two array are different:
Array
(
[0] => Array
(
[sud] => 60
[sad] => Array
(
[incharge] => Perusahaan
[perusahaan_id] => 1
[barang_id] => 3
[gudang_id] => 2
[stock] => 1
)
)
[1] => Array
(
[sud] => 23
[sad] => Array
(
[incharge] => Perusahaan
[perusahaan_id] => 1
[barang_id] => 4
[gudang_id] => 1
[stock] => 2
)
)
)
I want to move the array of [sud] into [sad] array, and named it as quantity.
This is my codes which generate the array above:
if($q->num_rows() > 0)
{
foreach ($q->result() as $row => $rows)
{
$data[] = $rows;
$stock[] = $rows->stock;
}
}
$i = -1;
foreach ($update as $updates)
{
$i++;
$test3['sud'] = $stock[$i];
$test3['sad'] = $updates;
$happy[] = $test3;
}
print_r ($happy);
What I want to do here actually is to check if the number of array [stock] => value is not bigger than the number in array [sud].
Please help, thanks in advance.
If I understood well, you want to change it like this:
if($q->num_rows() > 0)
{
foreach ($q->result() as $row => $rows)
{
$data[] = $rows;
$stock[] = $rows->stock;
}
}
$i = -1;
foreach ($update as $updates)
{
$i++;
$test3['sad'] = $updates;
$test3['sad']['quantity'] = $stock[$i];
$happy[] = $test3;
}
print_r ($happy);

Fetch all results from database using mysqli [duplicate]

This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 2 years ago.
please check out my code below. With that class I am able to display results like so:
$connectTest = new testResults();
$test = $connectTest->grabResults(test, id, id);
echo $test['id'];
echo $test['name'];
echo $test['address'];
In my database I have several fields in the "test" table. I go to my page using index.php?id=1. With this I am displaying just the results from one row because it grabs all results WHERE id = 1.
What I need is the class below to display multiple results. It just displays one row. But if I have multiple rows with id = 1 I would like to display these results, but I cannot get it to work. I have tried a lot of things but I always end up with just one result.
class:
class testResults
{
public function grabResults($table, $field, $id)
{
$result = $this->db->mysqli->query("SELECT * FROM $table WHERE $field = $id");
$resultData[] = array();
if(!$result)
{
return false;
}
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
foreach ($rows as $resultData)
{
return $resultData;
}
}
}
Edit:
Array ( [id] => 25 [name] => test [status] => 1 )
Array ( [id] => 25 [name] => test [status] => 3 )
Array ( [id] => 25 [name] => test [status] => 5 )
Array ( [id] => 25 [name] => test [status] => 4 )
Array ( [id] => 26 [name] => test [status] => 1 )
Array ( [id] => 26 [name] => test [status] => 3 )
Array ( [id] => 27 [name] => test [status] => 1 )
Array ( [id] => 27 [name] => test [status] => 3 )
Array ( [id] => 27 [name] => test [status] => 5 )
Array ( [id] => 27 [name] => test [status] => 4 )
Array ( [id] => 27 [name] => test [status] => 2 )
Array ( [id] => 27 [name] => test [status] => 4 )
Array ( [id] => 27 [name] => test [status] => 1 )
I am getting results as above, any way to easily display these results in an echo? For each id there are different results, so results will vary with each query. So I would like to display results in a table for example like so:
echo '<table>
<tr>
<td>$id</td>
<td>$name</td>
<td>$status</td>
</tr>
</table>';
So all results will be displayed like in a while loop.
You can just return the array from function and then loop in your script
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
The you can loop in your script
$test = $connectTest->grabResults(test, id, id);
foreach($test as $value)
{
print_r($value);
}
Upon OP edit
If you need to print them separate you can access all elements with variable name and scopes with keys as follow
$test = $connectTest->grabResults(test, id, id);
echo '<table>';
foreach($test as $value)
{
echo '<tr>
<td>'.$value['id'].'</td>
<td>'.$value['name'].'</td>
<td>'.$value['status'].'</td>
</tr>';
}
echo '</table>';
Since you are passing the full resultset to another layer for processing, you can skip the loop to generate an array of associative arrays from the resultset.
class testResults {
public function grabResults($table, $field, $id) {
// For the record, I feel a prepared statement is in order here...
$result = $this->db->mysqli->query("SELECT * FROM $table WHERE $field = $id");
return $result->fetch_all(MYSQLI_ASSOC); // just in case you wanted to see the column names
}
}
Then when you want to generate an html table from the returned array of associative arrays, use implode() as a flexible solution that doesn't care if you ever change the number of columns being passed in -- it will handle an indefinite number of columns.
if ($resultset = grabResults("tests", "name", "test")) {
echo "<table>";
foreach ($resultset as $i => $row) {
// if (!$i) { echo "<tr><th>" , implode("</th><th>", array_keys($row)) , "</th></tr>"; }
echo "<tr><td>" , implode("</td><td>", $row) , "</td><tr>"
}
echo "</table>";
}
It looks like you are returning a single row of your results with this bit of the function:
foreach ($rows as $resultData)
{
return $resultData;
}
You should just return the whole thing instead.
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
return inside foreach() iteration means stop right after first iteration. Therefore you will be always getting only the first result.
You'd better write this as:
public function grabResults($table, $field, $id)
{
$result = $this->db->mysqli->query("SELECT * FROM $table WHERE $field = $id");
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}

Retrieve subarray of array by key value

I have the following array (example, real one is larger)
Array
(
[0] => Array
(
[984ab6aebd2777ff914e3e0170699c11] => Array
(
[id] => 984ab6aebd2777ff914e3e0170699c11
[message] => Test1
)
[1] => Array
(
[ca403872d513404291e914f0cad140de] => Array
(
[id] => ca403872d513404291e914f0cad140de
[message] => Test2
)
)
[2] => Array
(
[ca403872d513404291e914f0cad140de] => Array
(
[id] => ca403872d513404291e914f0cad140de
[message] => Test3
)
[3] => Array
(
[ca403872d513404291e914f0cad140de] => Array
(
[id] => ca403872d513404291e914f0cad140de
[message] => Test4
)
)
)
Now I want to somehow "access" the subarray with a given id, e.g. access the subarray with ID 984ab6aebd2777ff914e3e0170699c11 and then proceed to use this array in a foreach like this..
foreach ($array_with_specific_id as $event) {
echo $event['message'];
}
Is this possible?
Edit:
DB code to produce array in my model:
public function get_event_timeline($id)
{
$data = array();
foreach ($id as $result) {
$query = $this->db->query("SELECT * FROM event_timeline WHERE id = ?", array($result['id']));
foreach ($query->result_array() as $row)
{
array_push($data, array($row['id'] => $row));
}
}
return $data;
}
When populating your array from the database you can cerate an additional $index array like the following scheme:
$index = array (
'984ab6aebd2777ff914e3e0170699c11' => ReferenceToElementInData,
'ca403872d513404291e914f0cad140de' => ReferenceToElementInData,
// ...
)
This can give you quick access to the elements via their id without an additional foreach loop. Of course it will need additional memory, but this should be ok as you will only save refrences to the original data. However, test it.
Here comes an example:
public function get_event_timeline($id)
{
$data = array();
// create an additional index array
$index = array();
// counter
$c=0;
foreach ($id as $result) {
$query = $this->db->query("SELECT * FROM event_timeline WHERE id = ?", array($result['id']));
// every entry in the index is an array with references to entries in $data
$index[$result['id']] = array();
foreach ($query->result_array() as $row)
{
array_push($data, array($row['id'] => $row));
// create an entry in the current index
$index[$row['id']][] = &$data[$c];
$c++;
}
}
return array (
'data' => $data,
'index' => $index
);
}
Now you can access the elements via the index array without an additional foreach loop:
$entry = $index['984ab6aebd2777ff914e3e0170699c11'][0];
If there are multiple results per $id (as you mentioned in the comments you can access them using index greater then zero:
$entry = $index['984ab6aebd2777ff914e3e0170699c11'][1];
$entry = $index['984ab6aebd2777ff914e3e0170699c11'][2];
You can get the count of items per $id by calling
$number = count($index['984ab6aebd2777ff914e3e0170699c11']);
That's much the same like indexes that where used in databases to speed up queries.
I'd probably just get rid of the containing array as it seems unnecessary. However, you could do something like:
function get_message($specific_id, $arrays) {
foreach($arrays as $array) {
if(in_array($specific_id, $array)) {
return $array['message'];
}
}
}
I haven't had a chance to test this, but it should work.
function doTheJob($inputArray, $lookingFor) {
foreach ($inputArray as $subArray) {
foreach ($subArray as $subKey => $innerArray) {
if ($subKey == $lookingFor) {
return $innerArray;
}
}
}
return NULL;
}
Alternatively, you can use array_filter instead of outer foreach.

creating multidimensional array from single array

i have a html form in which i use array like this (name="courts[]"). when it send data to php file i use foreeach loop to create multidimensional array for inserting records in mysql. In php file i write foreeach loop to iterate like this
$data = array();
$i = 0;
foreach ($court_name as $result)
{
$data[] = array(
'court_name' => $result[0]
);
$i++;
}
it display result this
Array
(
[0] => Array
(
[court_name] => P
)
[1] => Array
(
[court_name] => S
)
)
instead of this
Array
(
[0] => Array
(
[court_name] => Punjab
)
[1] => Array
(
[court_name] => Sindh
)
)
(referring the outputs) in your loop, $result contains court name. So if you use $result[0], you get first character of string.
Try this:
foreach ($court_name as $result)
{
$data[] = array(
'court_name' => $result
);
$i++;
}
foreach loop gives you one element of array ($result) now you access to the first character of value via $result[0], change it to $result
foreach ($court_name as $result) {
$data[] = array( 'court_name' => $result );
}

Categories