I have the following structure:
$positions = array();
$salaries = array();
$registers = ['Position' => $positions, 'Salary' => $salaries];
Since I created the positions and salaries associative arrays at the beginning using the array() syntax I assumed that later in the code I can just write:
$salaries += [$name => $salary];
But found out that at the end when tried to get some data using the registers array:
$registers['Position'] or $registers['Salary'] after I've done some filtering everything was empty and I had to reference it via registers to actually put data in:
$registers['Salary'] += [$name => $salary];
or create the registers array later in the code near the end of the script when the other arrays - positions and salaries were already full with the needed data.
My question is - since I put positions and salaries as values inside registers array does that mean I lose the ability to reference them as separate / independent arrays. I created them as described with that purpose in mind and registers array is for filtering purposes and I made it at the beginning so I have all that code at the very top of the script.
Will be very grateful for any info on the matter.
Related
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.
I have a javascript that formats an HTML table that takes some parameters to configure it. I also have a reports table in mysql that contains definitions of my reports: a field for the report name, description, sql, footer, permissions, report status and some report specific parameters. I build up the parameters as an array so that I can set defaults that can then be overwritten by other processes before being passed to a process that turns that array into the javascript parameters.
We use PHP to build reports based on the information in the table and it merges an array of "default parameters" with an array of "report specific parameters" . Before we put the report definitions into a database there was a function for each report that used array_merge that merged the default parameters array and the report specific parameter array.
eg
$defaultparameters = array (
'base_path' => "'/inc/plugin/'",
'btn_reset' => "'true'",
'enable_default_theme' => "'true'");
$thisReportParameters = array (
'extensions' => "[{ name: 'sort', types: ['String', 'String', 'String','String', 'String','String', 'Number']},'col_2'=> "'multiple'",'col_3'=> "'select'");
$parameters = array_merge ($defaultparameters,$thisReportParameters);
This array is then passed to a function that builds the javascript for the page.
Now we've put all the reports into a table I'm having trouble pulling out the report specific parameters into an associative array.
The default parameters are now set in the report class as a property of the report object. I want to pull the additional report specific parameters from the database into an array to combine the two.
When I added 'col_2'=> "'multiple'",'col_3'=> "'select'" to the database and brought it back as an array it put the whole string in as element [0] in the array.
ie
Array ([0] => "'col_2'=> "'multiple'"'col_3'=> "'select'"")
as opposed to
Array([col2] =>"'multiple'",[col_3]=> "'select'")
I considered just adding the string from the DB to the end of the javascript configuration but this would not overwrite any settings that were already defined in the default settings array so I need to add it to an array first so that when it merges it overwrites the any defaults where the keys are the same.
The report specific options are many and varied in their format so I can't feasibly create a field for each.
I thought about exploding the string on , then parsing the pairs to build the array but the value can have "," in it as well so that might mess up the exploding.
There's probably a really neat way of achieving this but at the moment it escapes me...
Any suggestions welcome
C
You could serialize your arrays.
There's also an option to encode them in JSON which may be better if your DB is postgres - it has some built-in support for things like that and it would be easier to work with your data using some other language if need ever arises.
In any case, be sure to properly sanitize your data before trying to put it into the DB.
Background:
I have a class in this application I'm building whose job is:
__construct: $this->data = $this->mongoDB->collection->findOne();
Intermediate functions are employed to manipulate the data in tens of different ways each request. One manipulation could trigger one which would trigger another. This allows me to do unlimited updates to the mongo document with just one query, as long as $this->data['_id'] remains the same. This is the only place where data manipulation of this specific collection is allowed.
__destruct: $this->monboDB->collection->save($data)
Data is then read back, json_encode'd and sent to Javascript to draw the page
Intention:
I intended to delete a member of an array by looping through said array, matching a value within it, and unsetting that. Example:
foreach($this->data['documents'] as $key => $val){
if($val == $toBeDeleted){
unset($this->data['documents'][$key];
}
}
Then, this would be saved to the DB when the script finishes.
Problem:
When javascript reads back the data, rather than having ['a', 'b', 'd'], I had {'0': 'a', '1': 'b', '3': 'd'} - which can't be treated like an array and would pretty much break things.
I had this question half typed out before my a-hah! moment, so I figured I'd post my own answer to it too for future reference.
In php, an associative array and an array are all the same. You can have out of order keys, nonconsecutive keys, and almost any key that you'd like to use in calling your array member. Most, if not all, php array functions work with any array key. Objects are a totally different thing.
That being said, Javascript doesn't share the same rules for arrays. A javascript array must have consecutive keys starting at zero, otherwise it is an object. MongoDB is similar to Javascript in this way.
When php converts an object to be used in MongoDB or in Javascript, if the php array doesn't follow that rule, it becomes a Javascript object.
The problem was after unsetting an array index, it left a gap, causing nonconsecutive array keys, causing it to become an object. Simple fix would either be array_slice($array, $key, 1) or $array = array_values($array)
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).
Hi can we create two dimensional array using php session. If possible how to unset values randomly.
No, PHP does not implement multi-dimensional arrays. However an element of an array can be an array itself. And any PHP data item can be stored in the session (however resources become meaningless outisde the thread they were initialized in, and objects require class definitions to be referenced from the session).
e.g.
<?php
$two_d=array(
array(1,2,3),
array(4,5,6),
array(7,8,9),
array('#','.','=')
);
$two_d[3][2]='*'; // was '='
how to unset values randomly
This would be an oxymoron in a 2-dimensional array. But is perfectly valid in the context of an array of arrays:
unset($two_d[1]); // removed the whole second row from the above
unset($two_d[0][1]); // $two_d[0] is now array(1,3)
$_SESSION['whateverValue'] = Array(
1 => Array (
'a','b','c','d'
),
2 => Array (
'q','w','e','r','t'
)
);
Voila, a two-dimensional array, in a session.
The session variables are in no way special while the script is executing. Their only "magic" is that they are unserialized at session_start() and serialized at session_close()