associative array overwriting entries php - php

I am trying to build an associative array to save the following information. A url, a word, and a frequency (# of occurrences of that word on that webpage).
I want to be able to access the information where I enter a string for the url and word and receive the frequency, like this:
$test["somewhere.com"]["biology"] => 5
$test["somewhere.com"]["auto"] => 10
$test["elsewhere.com"]["biology"] => 7
Right now I am pulling the information out of a db one row at a time and am trying the following:
$test["$url"] = array("$word" => "$freq");
After every iteration it gets over written. How do I change the syntax to avoid this situation? Is it possible to build the structure I want?
Thanks.
EDIT:
I was assigning values to array in a while loop. I made the mistake of initializing the array within the loop. I wasn't overwriting entries, I was
re-initializing the array unintentionally. That was my problem.

You are reassigning $test["$url"] as a new array each time. Use the full path:
$test[$url][$word] = $freq;
Also, no need for the quotes.

Instead of overwriting the first level contents, declare a new property for it. (without knowing how are you getting your urls, words and frequencies, the following is just an example)
$test = []
foreach($urls as $url => $words) {
$test[$url]=[];
foreach( $words as $word => $freq) {
$test[$url][$word] = $freq;
}
}
However, this looks awfully like trying to build an associative array that's already built.

Related

How to write a code for each array within an array

I am new to this so please do not judge.
I have transformed a .csv file into an array([0]=>array([0]=>string(), [1]=>string())[1]=>array([0]=>string(), [1]=>string()) etc. So I can access it numerically i.e. $the_big_array[1][1]
Now I want the program to write a couple of lines of code for each array within an array.
Basically what I am doing is creating a table like this that will be encoded in json.
$request['AddPrice'][0][variable1] = $the_big_array[1][2]
$request['AddPrice'][0][variable2] = $the_big_array[1][3]
and I want different values loaded for and from each line of .csv file/$the_big_array
$request['AddPrice'][1][variable1] = $the_big_array[1][2]
$request['AddPrice'][1][variable2] = $the_big_array[1][3]
I am stuck at foreach function as I cannot grasp how to make it execute certain action for each array within an array.
You have to use a foreach loop for every array dimension.
If You have 2 dimensions, like in $the_big_array[1][1], go through the first dimension with your first loop. Inside this loop, do another foreach to go through your second dimension.
so I have fixed this problem. Perhaps the question was not clear enough.
What I did was to create arrays with maximum occupancy for each of my rooms and add nested foreachloop for each occupancy, so it has to repeat until maximum occupancy is reached and only then it can iterate to the next key in the first foreachloop.

Unnecessary array wrapper

I am stumbling on something annoying and hope you can shed some light. I am generating an array via PHP MySQL query. My WHILE statement is as follows:
$model[constraints][d][] = array($row['Node'] => array("max" => $row['dem'], "min"=> $row['dem']));
The problem is that each new array added to $model[constraints][d] gets enclosed by an array. See screenshot below:
I don't want there to be array "0" around Norway. I would like to be able to access my values as follows:
$model[constraints][s][Norway][max]
Right now, the only way I can access that value is by doing the following:
$model[constraints][s][0][Norway][max]
How should I amend my while statement to get the desired array? Thank you for your time.
Before the loop you could do:
$model[constraints][d] = array();
And then just change the statement inside the loop to:
$model[constraints][d] += array($row['Node'] => array("max" => $row['dem'], "min"=> $row['dem']));
Here's a live demo

Push or Merge data into existing Array

When working with existing code, it takes one array and places it into another in the fashion shown below.
I believe the empty brackets are the same thing as simply pushing it and appending it to the first available index.
$g['DATA'][] = $p;
After this is done, I have my own array that I would like to append to this as well. I tried using array_merge() with $g['DATA'][]as a parameter, but this is invalid for obvious reasons.
My only thought is to create a foreach loop counter so I can figure out the actual index it created, however I have to assume there is some cleaner way to do this?
Just simply use the count() of your $g["DATA"] array as index and then you can merge it like this:
$g['DATA'][count($g["DATA"])-1] = array_merge($g['DATA'][count($g["DATA"])-1], $ownArray);
//^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^
// -1 Because an array is based index 0 -> means count() - 1 = last key

How to translate txt file settings into php array

I have text file containing values like this:
varname:
{
varname2: value
varname3:
{
varname4: value
}
}
I need to get this somehow into php array like this:
array(
varname => array
(
varname2 => value
varname3 => array
(
varname4 => value
)
)
)
How can i do this?
I have tried looping through file and trying to make values like that but it gets very tricky when there is multiple level array. Spent many hours without luck...
I suggest you (if you can) to change your file format to a JSON format, that is very similar to your format now:
{"varname":{"varname2":"value","varname3":{"varname4":"value"}}}
Then you can read the file and use json_decode to obtain the array in a very simple form. Here I write the code for decode json to array and echo it:
$s = file_get_contents('datos.js');
$ar = json_decode($s, true);
print_r($ar);
It depends on how much of a hack you want it to be. If you have a true defined format and want to be strict you'd start with a lexer. See http://wezfurlong.org/blog/2006/nov/parser-and-lexer-generators-for-php/ or https://github.com/nikic/Phlexy
On the other hand you could also make it in two steps (depending on how complicated the now shown use cases are).
Replace all leading spaces and replace : \n{ with : { for easier parsing.
Write a recursive parsing function. In every line everything before : is the variable name, everything after the value. If the value is { to a recursion until } and use the result as the value.

creating a multidimensional array from arrays in php

I'm trying to create an array of bar objects in php which consist of seven different attributes. The code I am using for this array is as follows:
$barsArray = array();
for($i = 0; $i < count($barNameArray); $i++)
{
$barsArray[] = array('BarName' => $barNameArray[$i], 'first' => $firstCover[$i], 'timeFirst' => $firstTimes[$i],
'second' => $secondCover[$i], 'timeSecond' => $secondTimes[$i],
'third' => $thirdCover[$i], 'timeThird' => $thirdTimes[$i]);
}
I have checked to make sure that all the other arrays are as I intend them. I just need to get this into one array of objects. Is this method completely off? Also, If I wanted to test to make sure that the correct objects are in the correct locations in a multidimensional array, how would I go about do that?
Thanks!
That code looks fine (although you may want to cache the count instead of performing it repeatedly).
I can't say for sure, not knowing your greater purpose, but you may want to make $barsArray an associative array by the bar name. To do that, use $barsArray[$barNameArray[$i]] =, instead of $barsArray[] = (and of course remove the BarName property). This would not keep it in the original ordering, but would make getting a particular bar easier.
You can get an element from $barsArray like so: $barsArray[3]['first'] (or $barsArray['some_bar_name']['first'] if you change it to an associative array).

Categories