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).
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.
Say, we make an array like this:
$arr = Array
(
2 => 'c',
1 => 'b',
0 => 'a'
);
When you pass it to array_pop():
array_pop($arr);
And the "last" element would be poped off, which has the index of zero!!
print_r($arr);
Result:
Array
(
[2] => c
[1] => b
)
So, what's the purpose of index?
Isn't it just a different way of saying "numeric keys of associative arrays"?
Is it only PHP dose so, or all the languages treat arrays like this?
Not all languages do this, but PHP does, because PHP is a little weird. It implements arrays more or less like dictionaries. PHP does offer some functions like ksort though, which let you sort the array by key.
And that's what this is: a key. An array has indexes as well, so what you got, is an array where item 2 has key 0. And that's where the confusion starts continues.
PHP: a fractal of bad design has a whole chapter about arrays. Interesting reading material. :)
The reason for this behavior is because arrays in PHP are actually unordered maps.
Because of this, don't think of accessing the arrays in terms of indexes, think of it in terms of keys. Keys can be numbers and they can be strings, but the result is the same; you're still using a map, not a true "array".
Once you accept that fact, you'll understand why PHP includes functions like ksort() for sorting an array by keys and why array_pop() doesn't always remove the highest key value.
It's a PHP thing. Other languages usually provide other structures to provide what is the default behaviour for arrays on PHP. JavaScript for instance will always sort the array:
a = [];
> []
a[1] = 'a';
> "a"
a[2] = 'b';
> "b"
a[0] = 'c';
> "c"
a
> ["c", "a", "b"]
In Java you would need to use a Hash Map or something else to do Associative Arrays. PHP handles data structures more loosely than other languages.
The index allows you to identify and access the elements of the array.
the reason is simple HashTables.
in php internal functions often use HashTables. basically an array is some data in memory and like in C - an array index can only hold integer values but not in php.
php solves this with hashtables. if you asign a index example foo this value is not directly assigned as foo it gets hashed and maybe end internal as 000000000111 and other hash functions.
so php doesn't work directly with your assigned value and this is the reason why you can set an array index like 0 as last index element. internal php work with hashtables that have a "list" with values which index value is assigned to which position in the array.
I have an array $cat1 including
cat1[0]=>16 and cat1[1]=>16.
I also have this array:
$url_vars = array('text'=>$event->properties['text'],'SearchResultPagerPage'=>$thenextpage);
I need to put these combined into this URL function:
$this->URL('SearchResult','',$url_vars);
So that the resulting URL needs to look like this:
/SearchResult.html?text=cat&SearchResultPagerPage=1&cat1[]=1&cat1[]=16
Currently, if I combine them, I get this as the resulting combined array:
Array
(
[text] => cat
[SearchResultPagerPage] => 1
[0] => 1
[1] => 16
)
and this as the resulting URL:
SearchResult.html?&text=cat&SearchResultPagerPage=1&1=16
How do I form this so that it says cat1[]=1&cat1[]=16 instead of 1=16?
Thanks very much for any help anyone might offer!!
If you MUST use the URL function $this->URL('SearchResult','',$url_vars); then one idea is to use indices in the cat1 array. That is:
$url_vars["cat1[0]"] = 1;
$url_vars["cat1[1]"] = 16;
This will result in your query string having
...&cat1[0]=1&cat1[1]=16
with the []'s probably escaped, but perhaps your server script can properly accommodate these indices. It is worth a try. Otherwise you'll have to generate the URL outside of the URL function, because you can't have a php array with identical keys "cat1[]" but two separate values.
EDIT: One other thing to try in case your URL function is intelligent enough:
$url_vars["cat1"] = [1,16];
I have PHP $_SESSION arrays that have an undefined amount of elements. Is it possible to initialise all the values to 0, or do I have to check whether the value is NULL and then set to 0 every time I check a value?
Edit: I'm sorry for the vagueness of my question.
I have an undefined amount of levels, and I'd like to store all the scores of each level in that array. Currently my amount of levels is fixed, so I am currently just writing:
$_SESSION['totals'] = array(0,0,0,0,0);
And then when adding manipulating the data, I simply increment/add a certain amount to that element.
Now I'd prefer to have the same ease of directly incrementing/adding values to certain elements without needing to check whether a value is NULL or something like that...
Edit 2: edited my code as follows:
$_SESSION['totals'] = array();
if(array_key_exists($row['level']-1,$_SESSION['totals'])){
$_SESSION['totals'][$row['level']-1]++;
}else{
$_SESSION['totals'][$row['level']-1] = 1;
}
And it seems to work. Thanks fellas!
You can use array_fill_keys function to fill an array with specified value for defined keys:
$keys = array('foo', 'bar', 'baz');
$output = array_fill_keys($keys, 0);
Defining an array with initial values is defining an array with a length. This does not prevent you from adding or removing elements from the array:
// initial array
$myArray = [0, 0, 0, 0];
print_r($myArray); // would output Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0)
$myArray[] = 1;
print_r($myArray); // would output Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 1 )
$_SESSION contains only what you put into it. Just make sure you add 0 instead of null the first time you add something.
If you need to do this later, I think your design might be bad. But anyway, $_SESSION is like a normal array, so you can just use PHP's array function to traverse the array and check or change each value.
PHP arrays aren't really arrays you might know from other languages. They really are more like linked lists with hash access.
What this means is: You either know all the string array indices you want to use, and either make sure they exist, or you check their existence every time you access them which might fail.
For numeric indices, the same thing applies. You might have an array with indices 1, 2 and 4 present, but if you run over it with only a for loop, you will trigger a notice when accessing the nonexistant element 3.
Use foreach loops whenever you want to iterate arrays. Check with isset() whenever you want to document that the array value might not be present. Don't do it if you know or assume that the array element MUST be present - if not, you get the notice as a reminder that your code is working on a data structure that is NOT what you thought it is. Which actually is a good thing. Then fix it. :)
Your best bet would be to abstract your session stuff by creating facade methods, or getters and setters around the session variables rather than access them directly. This way you can return a default value if the one you're after doesn't exist.
I've used array_key_exists() to check if the index is set. If it is not, I display 0 or add store a certain value in that field, else I show the value of that index or add certain value to that field.
Credit to Sven for bringing that up.
to check what u have in your sessions, loop tru it. not sure if this is what u are asking.
foreach($_SESSION as $x=>$y)
{
if(empty($x)) { //do something }
}
I'm working with a long list of name - value pairs and I will be checking with this list alot so I wanted to know what you guys think is the fastest way to do named value pair look ups. An example of my problem is as follows:
Using PHP
The variables are on the left side with the string value they are suppose to represent. There are roughly 68 variable with corresponding string values.
rKid = Hiking
rSpo = Sports
rFly = Flying
I will need a look up every web page to see what each of the variables could correspond to.
I was thinking of an array -> list value look up, but unsure of how to implement that.
Associative arrays in PHP are in fact hash maps, so lookup by key is very efficient. What you need is this structure:
$map = array(
'rKid' => 'Hiking',
'rSpo' => 'Sports,'
'rFly' => 'Flying'
);
And the lookup is straightforward:
echo $map['rKid']; // 'Hiking'