Creating array from query results and pushing multiple values to associated key - php

I have an object of query results. Each result has two columns: abbreviation and text. I need to create a new array, where I want to store values from 'text' column grouped by values in 'abbreviation' column.
I tried this:
foreach ($results as $result) {
$results_by_book_abbreviation[$result->abbreviation] = $result->text;
}
What I get is an array with multiple keys, but each key has only one value, but my object has multiple values with the same key.
It worked in PHP 5.5.38, now I have PHP 7.0.13

Array KEYS are UNIQUE, so if you load a key more than once you are overwriting it's contents each time.
So create an array below $results_by_book_abbreviation[$result->abbreviation] like this
foreach ($results as $result) {
$results_by_book_abbreviation[$result->abbreviation][] = $result->text;
// the change ^^
}
This would have been wrong in any version of PHP so it is not related to you changing the version of PHP that is running this code

You need to create an array of array as follows:
foreach ($results as $result)
{
if(!isset($results_by_book_abbreviation[$result->abbreviation]))
{
$results_by_book_abbreviation[$result->abbreviation] = array();
}
$results_by_book_abbreviation[$result->abbreviation][] = $result->text;
}

Related

Pushing key/value pairs to an array, loses key out of forloop

I get my data from the database, but want to add 2 keys to them. So I add them in a for loop. If I dump (simple function that prints the array with pre tags) the single result in the for loop, it's correct, when I dump the 2dimensional array outside of it, it doesn't have the keys anymore..
For some reason it doesn't push it to the 2dimensional array?
$results is a 2dimensional array btw.
//add amount and subtotal to the array's elements
foreach ($results as $result) {
$result['amount'] = $sessionShoppingCart[$result['artikelnummer']][1];
$result['subtotal'] = $result['amount'] * $result['Verkoopprijs'];
$this->dump($result);
}
$this->dump($results);
To change an array within the foreach you can do two things.
Reference the array value with &:
foreach ($results as &$result) {
Or use the key and modify the array:
foreach ($results as $key => $result) {
$results[$key]['amount'] = $sessionShoppingCart[$result['artikelnummer']][1];
$results[$key]['subtotal'] = $result['amount'] * $result['Verkoopprijs'];
}

Removing Duplicate string from for each loops

I am having an issue removing duplicates from the result of a foreach loop.
The problem more so is the process of how i have the data.
Here is grab the data i need.
$results = mysql_query($query);
while($rows = mysql_fetch_assoc($results)){
extract($rows);
I am trying to grab a column of item_specifiations. Within this column there are multiple data, separated by commas. Some items have more data that others, some are lacking certain data.
$specs = explode("," , $item_specification);
I separate the data using the above method.Then i run the loop to show the data for each item in the DB.
foreach($specs as $spec => $key ){
This now returns every data separated for each item (UPC, PRODUCT_NAME, ETC), which is exactly what i need. But i need only the "BRAND" of the item. So i do the following.
if (strpos($key, 'Brand') === 0) {
$brand = explode(':', $key);
}
Now the problem i am having is certain items having duplicate brand names.
So i want to remove any strings that are returning. The problem is, since this is a loop, there is no way to compare the strings with each other. Each is its own array, so i am dealing with multiple multi-dimensional arrays. I cant figure a way to push them into 1 array then compare, or using something like unique_array.
Any suggestions or help would be appreciated. I have been stuck for awhile.
Use array_unique:
$var = [];
foreach($specs as $spec => $key) {
if(strpos($key,'Brand') === true ) {
$brand[]= implode(',', array_unique(explode(', ',$key)));
}
}
print_r($brand);

Dynamic Table Iteration PHP MySql

Suppose I have an SQL Statement that looks like:
SELECT * FROM myTable;
Now back in PHP I have a result array $result[], How can I iterate through that array and print out the values if I don't know the column names? Can I interrogate the array somehow?
Background: I have a table, I've rendered the table headings based on the a metadata table, now I need to populate the data, but I only want to pull out the field names that match the table headers and insert them into the HTML Table.
This process is happening dynamically, every table is different and has different field names (discovered by interrogating the metadata), but shares the same php code, so it needs to be flexible and smart enough to figure out what to render.
Edit: I now understand that your $result is an array of arrays.
foreach ($result as $row) {
foreach ($row as $key => $value) {
print "column $key has value $value\n";
}
}
Or you can call array_keys($row) to return the keys of an associative array.
You can use foreach loop with key-value pair in that case.
You can use it like this,
foreach($result as $key=>$value) {
//$key returns the key of $result array
//$value returns the respective value of that key
}

How to combine multiple arrays

First off this question in in relation to this question. My issue is that a friend of mine has upwards of around 300 or so arrays that she needs to insert into the database. I get the database part as you notice in the question I linked I have that part down. My question however arises on just how exactly I am supposed to get all the arrays and bring them together so that I could could do a foreach on the arrays and check if a value is an array, if it is then use the arrays name as the table in the INSERT query.
This is my updated code :
$colors['Colors_All'] = array("Black","Charcoal"); // Add unique indexes
$colors['Colors_Bright_All'] = array("Silver","White"); // Add unique indexes
$AllArrays = get_defined_vars(); // Get all defined vars
$Arrays = array(); // Set a default array
foreach ($AllArrays as $varName => $value) { // Run through all the variables set in the get_defined_vars
if(is_array($value) && $varName == 'colors') { // If it is an array and if the array is colors[] then
$Arrays = array_merge($Arrays, $value); // Merge those arrays into the new array
}
}
This will now give me access to all the data.
Here you go:
$colors['Colors_All'] = array("Black","Charcoal","Light_Gray","Silver","White","Gold","Bronze","Copper","Platinum","Navy","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Turquoise","Tiffany_Blue");
$colors['Colors_Bright_All'] = array("Silver","White","Gold","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Deep_Green","Forest_Green","Bright_Green","Violet");
$colors['Colors_Light_All'] = array("Light_Gray","Silver","White","Gold","Dodger_Blue","Deep_Sky_Blue","Light_Blue","Bright_Green","LightGreen","Light_Green");
// This will store the merged results of each array
$colorVars = array();
// Loop through all of the defined variables
foreach ($colors as $colorKey => $value) {
// Add the results of this array to the main $colorVars array
$colorVars = array_merge($colorVars, $value);
}

Storing array within an array using PHP

foreach ($topicarray as $key=>$value){
$files = mysql_query("mysqlquery");
while($file = mysql_fetch_array($files)){ extract($file);
$topicarray[$value] = array( array($id=>$title)
);
}
}
The first foreach loop is providing me with an array of unique values which forms a 1-dimensional array.
The while loop is intended to store another array of values inside the 1-dimensional array.
When the while loop returns to the beginning, it is overwriting it. So I only ever get the last returned set of values in the array.
My array ends up being a two dimensional array with only one value in each of the inner arrays.
Feels like I'm missing something very basic here - like a function or syntax which prevents the array from overwriting itself but instead, adds to the array.
Any ideas?
Step 1. Replace $topicarray[$value] with $topicarray[$value][]
Step 2. ???
Step 3. Profit
Make $topicarray[$value] an array of rows, instead of one row. Also, don't use extract here.
foreach ($topicarray as $key => $value) {
$rows = array();
$files = mysql_query("mysqlquery");
while($file = mysql_fetch_array($files)) {
$rows[] = array($file['id'] => $file['title']);
}
$topicarray[$value] = $rows;
}
Also, you should switch to PDO or MySQLi.

Categories