I have an array called $brand_terms. I'm accessing two objects in this array. In this case 'name' and 'slug'. I'm then trying to set values of these objects in an associative array called $values. The code is below:
$brand_terms = get_terms("pa_brand");
$values = array(
foreach ($brand_terms as $brand_term){
$brand_term->name => $brand_$term->slug,
}
);
The problem I have is with the separator ,. So the comma at the end of $brand_term->name => $brand_$term->slug,. If the loop is at the last value in the array, the comma is not needed and the the code is broken. Is there a nice way to remove this comma from the last iteration of the foreach loop?
Thanks
That syntax is completely wrong. You cannot have a loop within an array declaration.
Instead create the array, then push elements into it during the loop:
$brand_terms = get_terms("pa_brand");
$values = array();
foreach ($brand_terms as $brand_term){
$values[$brand_term->name] = $brand_$term->slug;
}
Actually, the problem isn't at all with the , literal, in fact that isn't valid PHP. You can't have a foreach loop inside of an array declaration.
The best approach is to define the array and then loop through the get_terms() return value as follows:
$values = array();
foreach( get_terms('pa_brand') as $term )
{
$values[$term->name] = $term->slug;
}
Related
I'm trying to loop an array from a database into an existing array. The two codes work well alone but I only get an error when trying to combine them.... for example...
The current array (which is a list of spammer databases) look as such...
$dnsbl_lookup=array(
"access.redhawk.org",
"all.s5h.net",
"blacklist.woody.ch",
);
While the array I am trying to add is as so...
$values = $myOptions['re_i_'];
foreach ($values as $value) {
echo '"'.$value['database'].'",';
}
And I end up with the following...
$dnsbl_lookup=array(
"access.redhawk.org",
"all.s5h.net",
"blacklist.woody.ch",
$values = $myOptions['re_i_'];
foreach ($values as $value) {
echo '"'.$value['database'].'",';
}
);
Which, of course, only returns an error. Does anyone know how to do this properly or if it is even possible?
It looks like you want to merge the $dnsbl_lookup values with the database column values in $myOptions, which you can do with array_merge and array_column:
$dnsbl_lookup = array(
"access.redhawk.org",
"all.s5h.net",
"blacklist.woody.ch"
);
$dnsbl_lookup = array_merge($dnsbl_lookup, array_column($myOptions['re_i_'], 'database'));
Demo on 3v4l.org
i have the following problem. i have a large array structure which i assign values from a sql statement:
$data[$user][$month]['id'] = $data->id;
$data[$user][$month]['company'] = $data->company;
...
...
and around 30 other values.
i need to clone this array ($data) and add a subarray like:
$data[$user][$month][$newsubarray]['id'] = $data->id;
$data[$user][$month][$newsubarray]['company'] = $data->company;
...
...
i need to clone it because the original array is used by many templates to display data.
is there a way to clone the array and add the subarray without assign all the values to the cloned array? this blows up my code and is very newbi, but works.
You can use array_map, check the live demo
if you want to pass parameter to array_map(), use this
array_map(function($v) use($para1, $para2, ...){...}, $array);
Here is the code,
<?php
$array =array('user'=> array('month'=>array('id' =>2, 'company' => 3)));
print_r($array);
print_r(array_map(function($v){
$arr = $v['month'];
$v['month'] = [];
$v['month']['newsubarray'] = $arr;
return $v;}
, $array));
You can iterate through the array with nested foreach loops.
It would look similar to this:
foreach ($data as $user=>$arr2) {
foreach ($arr2 as $month=>$arr3) {
foreach ($arr3 as $key=>$value) {
$data[$user][$month][$newsubarray][$key] = $value;
}
}
}
Your last level of array, you can create object, for holding data with implementing ArrayAccess. Then simply by reference, assign object in desire places. This way, you can hold 1 object and use it multi places, but if you change in one - this change in all.
Then you addictionaly, can implements __clone method to clone object correctly.
I have an array of arrays, and I am trying to foreach loop through and insert new item into the sub arrays.
take a look below
$newarray = array(
array("id"=>1,"quantity"=>2),
array("id"=>1,"quantity"=>2),
array("id"=>1,"quantity"=>2),
);
foreach($newarray as $item){
$item["total"] = 9;
}
echo "<br>";
print_r($newarray);
The result just give me the original array without the new "total". Why ?
Because $item is not a reference of $newarray[$loop_index]:
foreach($newarray as $loop_index => $item){
$newarray[$loop_index]["total"] = 9;
}
The foreach() statement gives $item as an array: Not as the real value (consuming array). That meaning it can be read but not changed unless you then overwrite the consuming array.
You could use the for() and loop through like this: see demo.
Note: This goes all the way back to scopes, you should look into that.
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.
How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
//create a new variable called $elem1 (or $other or $elemother, etc.)
//and assign it some default value 1
}
foreach ($myarray as $name) {
$$name = 1;
}
This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.
goreSplatter's method works and you should use that if you really need it, but here's an alternative just for the kicks:
extract(array_flip($myarray));
This will create variables that initially will store an integer value, corresponding to the key in the original array. Because of this you can do something wacky like this:
echo $myarray[$other]; // outputs 'other'
echo $myarray[$lastelement]; // outputs 'lastelement'
Wildly useful.
Something like this should do the trick
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
$myVars[$arr] = 1;
}
Extract ( $myVars );
What we do here is create a new array with the same key names and a value of 1, then we use the extract() function that "converts" array elements into "regular" variables (key becomes the name of the variable, the value becomes the value).
Use array_keys($array)
i.e.
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
$namesOfKeys = array_keys($myVars );
foreach ($namesOfKeys as $singleKeyName) {
$myarray[$singleKeyName] = 1;
}
http://www.php.net/manual/en/function.array-keys.php