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.
Related
Hi im a beginner in php i would like to ask how do i remove duplicates from multidimensional array using foreach loop. what do i have have to put inside the print_r part.
while($row =mysqli_fetch_assoc($result3))
{
$nodecontainer {"id"} = ($row ["left_skill"]);
foreach ($nodecontainer as $id => $leftskill)
{
print_r($nodecontainer);
}
}
You can do it like below:-
$nodecontainer = [];//define array
while($row =mysqli_fetch_assoc($result3)){
$nodecontainer[] = $row ["left_skill"]; //assign all values to array
}
$nodecontainer = array_unique($nodecontainer);//remove duplicate
print_r($nodecontainer); //check final array
Note:- BTW I will recommend you to use DISTINCT or GROUP BY inside query to remove duplicates. No need to do anything then at PHP end.
Seems pretty simple: extract all id values into their own array, run it through array_unique:
$uniquePids = array_unique(array_map(function ($i) { return $i['id']; }, $holder));
If you want to use PHP, use array_unique()
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 need to convert an structure like this:
$source[0]["path"]; //"production.options.authentication.type"
$source[0]["value"]; //"administrator"
$source[1]["path"]; //"production.options.authentication.user"
$source[1]["value"]; //"admin"
$source[2]["path"]; //"production.options.authentication.password"
$source[2]["value"]; //"1234"
$source[3]["path"]; //"production.options.url"
$source[3]["value"]; //"example.com"
$source[4]["path"]; //"production.adapter"
$source[4]["value"]; //"adap1"
into something like this:
$result["production"]["options"]["authentication"]["type"]; //"administrator"
$result["production"]["options"]["authentication"]["user"]; //"admin"
$result["production"]["options"]["authentication"]["password"]; //"1234"
$result["production"]["options"]["url"]; //"example.com"
$result["production"]["adapter"]; //"adap1"
I found a similar question but I can't adapt it to my particular version of the problem: PHP - Make multi-dimensional associative array from a delimited string
Not sure what problems you were running into, but the following works ok. See https://eval.in/636072 for a demo.
$result = [];
// Each item in $source represents a new value in the resulting array
foreach ($source as $item) {
$keys = explode('.', $item['path']);
// Initialise current target to the top level of the array at each step
$target = &$result;
// Loop over each piece of the key, drilling deeper into the final array
foreach ($keys as $key) {
$target = &$target[$key];
}
// When the keys are exhausted, assign the value to the target
$target = $item['value'];
}
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;
}
I have multiple rows getting returned from a database query.
I am able to get just a row at a time, but I want to put the rows in an array of objects like this:
$trailheads[] = new StdClass;
Loop
{
$trailheads[] = $trailhead; // Put each object into the array of objects
}
But when I try to loop through each array, I am having trouble extracting the values of each row. What is the right way to loop through the returned object and get the values?
The code that does not work is pretty basic:
$returned_obj->o->trailhead_name
But I am actually hoping be able to loop through each array element.
Maybe try casting to array in your for loop, this is untested and may not work as is but should get you on the right track:
foreach ($trailheads as (array) $key){
// $key is now an array, recast to obj if you want
$objkey = (object) $key;
}
i'm assuming your using mysql since you did not say...
you can use thsi function mysql_fetch_object()
<?php
$trailheads = array()
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result, 'trailhead')) {
$trailheads[] = $row;
}