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'];
}
Related
While I map all the links on a page that is contained in an array, I want to check if each of the links is inserted in this array and, if not, insert it.
I'm trying to use the code bellow without success because "foreach $arr" doesn't pass by in the new values.
include_once('simple_html_dom/simple_html_dom.php');
$arr = array('http://www.domain.com');
foreach ($arr as $key => &$item) {
$html = file_get_html($item);
// Find category links
foreach($html->find('a[href^=http://www.domain.com/dep/]') as $element) {
if (!in_array($element->href, $arr))
$arr[] = $element->href;
}
}
print_r($arr);
Important: I need to search and add value in the original array, not in the copy (foreach).
First of all
In foreach ($arr as $key => &$item) { every $item is a STRING. (As a warning told you). So you shouldn't use $item[] here.
Next pitfall: if you want to add new items to your $arr array symtax should be
$arr[] = $some_var;
But you shouldn't do this because every time you add items to $arr, this array increases and you iterate not over two elements array, but for example 3-elements or 4 elements. Do you expect this?
You should find new values, put them in some other array and then merge both arrays.
Or use #splash58 solution. It's even simplier.
I am trying to parse a json. I am running this in a foreach loop and if I do the following it works:
$places = array('restaurant', 'store', 'etc')
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
However, when I do the following, i.e. I change restaurant to $places (I need to do this since I have an array of different places and I want to parse all of them in a foreach loop) it doesn't work.
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}
Solution is changing $places to {$places}[0]
The $places array contains keywords, such as restaurant or store. So the [0] is referring to the first one in the json which is why it's needed.
Why do you have this in the first loop:
json[0]->restaurant[0]
json[0]->$restaurant[0]
But then in the next you have:
json[0]->$places[0]
json[0]->$places[0]
Perhaps you are parsing the JSON incorrectly and it should be:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}
And then in the first loop, you should do a similar edit to get rid of $restaurant[0]:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
Then again, unclear on what value $places has when you loop via foreach ($this->placesCachingTypes as $places) {. It does’t make sense what you would be looping through with the value of $places. And perhaps assigning that $places in the loop object of $json_decoded->json[0]-> is the source of your issues? Need more info from you to confirm this.
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);
}
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.
i am trying to create array like in the example i wrote above:
$arr=array('roi sabah'=>500,yossi levi=>300,dana=>700);
but i want to create it dynamic with foreach.
how can i do it ?
thanks.
You can access an array with foreach (and optionally create another one while going through the array's values). But if you only have data like a name and a number from your example, not stored in an array, you can't use foreach.
Another way to create the array you mentioned:
$arr = array();
$arr['roi sabah'] = 500;
$arr['yossi levi'] = 300;
// etc
And to access these values:
foreach ($arr as $key => $value) {
// $key is e.g. "roi sabah", and its value "500"
}