how to loop through array with dynamic keys in PHP - 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] ;
}
}

Related

Adding data to existing array after using array data

I have an array of data that is being created from a MySQL query which I am then using to create more data which I then need back in the array (or a new one) but I haven't been able to get this working at all.
Here is the code I have been trying to use:
$vars['items'] = $this->_query('SELECT customers.*, sites.site_name as `default_location`
FROM `customers`
JOIN `sites` ON customers.site_id=sites.id');
$a=array();
foreach($vars['items'] as $customer)
{
if($customer['record_to_use'] == '2')
{
$results = dns_get_record($customer['cust_mx'], DNS_MX);
$mx = min(array_column($results, "pri"));
$highest = array_filter(
$results,
function($item) use($mx) {return $item["pri"] === $mx;}
);
foreach ($highest as $mx)
{
$results = dns_get_record($mx["target"], DNS_A);
foreach ($results as $a)
{
$vars['items']['ip'] .= $a['ip'];
}
}
}
}
So I need the IP that gets created from each item in the array to get added into that array as $vars['items']['ip']
Thanks in advance!
foreach ($results as $a => $value)
{
$vars['items'][$a]['ip'] = $value['ip'];
}
That's what I needed :)
$vars['items']['ip'] .= $a['ip'];
.= is concatenation if that was a typo in your code.
Try $vars['items']['ip'] = $a['ip'];

Database information into separate arrays

here is what I'm trying to do. I'm retrieving information from a database via array. What is happening is the information from the previous array is going into the next array.
Here is the code:
$i = 0;
foreach ($array_name as $key => test_name) {
$id = $test_name['id']
foreach ($test_name['id] as $key => $test_id {
$data = ModelClass::Information($test_id);
$array_name[$i]['new_infroamtion'] = $data'
}
}
So right now based on the code data from the table is correctly going into the first array, however, information based from the first array is going into the second array..
Let me know if you need anymore information.
Thank you
You are using $array_name while you are iterating through $array_name. This is valid code if you want to do this, but I don't think you do. You need to change the second $array_name to something else.
$i = 0;
foreach (**$array_name** as $key => test_name) {
$id = $test_name['id']
foreach ($test_name['id'] as $key => $test_id {
$data = ModelClass::Information($test_id);
**$array_name**[$i]['new_infroamtion'] = $data
}
}
I did find a solution. What I had to do was add the following
$s = array()
Then in the for loop, I added the following code:
foreach ($test_name['id] as $key => $test_id {
$data = ModelClass::Information($test_id);
$s[] = $data
$array_name[$i]['new_infroamtion'] = $s'
}

Returning values from an array

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.

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

Foreach inside function

function dp(){
$this->load->library('heart');
$times = 35;
$i = 0; while ($i<$times){
$this->heart->test();
//10 newest
$query = $this->db->get('test', 10, 20);
//set variables from query
foreach ($query->result() as $getrow)
{
$data1 = $getrow->data1;
$data2 = $getrow->data2;
}
//for each data1; do go();
foreach ($data1 as $id){
$this->heart->go($id,$data2);
}
//increment $i
$i++;
}
}
Hey guys, here is my code. I am trying to get the most newest entries from the database, then setting them as variables. For each variable, I am trying to call a function to it passing $id (data1) and $data2. Will data2 be passed or do I need to do something like $data1 as $id && $data2 as $id2. I need to pass over $data1 and $data2 to go() which should be different everytime.
The problem here is I keep getting 'Invalid argument supplied for foreach()' whenever I try to run the code. Anyone know what the issue is here?
Thank you in advance.
I believe you actually want to be creating arrays of $data1 and $data2.
Currently you are overwriting the values in each of those variable each time through the first foreach loop.
$data1 = array();
$data2 = array();
//set variables from query
foreach ($query->result() as $getrow)
{
$data1[] = $getrow->data1;
$data2[] = $getrow->data2;
}
//for each data1; do go();
foreach ($data1 as $key => $id){
$this->heart->go($id,$data2[$key]);
}
Alternatively you could use data1 and data2 as the key/value pair of the array
$data = array();
foreach ($query->result() as $getrow)
{
$data[$getrow->data1] = $getrow->data2;
}
//for each data1; do go();
foreach ($data as $key => $value){
$this->heart->go($key, $value);
}
You can do it all with a single foreach loop without building unnecessary data arrays:
foreach($query->result() as $getrow) {
$this->heart->go($getrow->data1, $getrow->data2);
}

Categories