I am trying to access elements from a multidimensional array in an object. For example, let's assume there is some class Foo that has a variable called $phone that represents the multidimensional array.
$phone -> structure will look like
Array {
"home" Array(1) {[0] = "555-1212"},
"work" Array(2) {[0] = "555-1234", [1] = "555=5434"},
"other" Array(1) {[0] = "555=9090"}
}
Note: We can't assume we know the keys.
I can access a value by giving explicit keys, i.e.,
$foo->phone["home"][0]
The problem comes to when I don't explicitly know the keys and pull them from elsewhere.
For example if $type="phone", $subtype = "home", and I want the first entry I would expect to use:
$object->$type[$subtype][0]
to get the value, but I get an error and it doesn't think it is an array. I am not sure where the error is.
The next thing would be to add elements to the lowest level array. I assume the following would work, but doesn't:
array_push($object->$type[$subtype], $value)
This mutidimensional array would allow me to store phone numbers labelled by keys in a single nested structure. If this is overcomplicating the issue please let me know. The reason I chose this structure is because the keys can be anything the user customizes.
Thanks.
I believe this will work if you save $object->$type as it's own variable, then access that variable to go deeper in the array.
Related
It seems that all my questions are so basic that I can't find answers for them anywhere, probably because all the guides assume you have at least some basic knowledge. Anyway, on to my question...
With regard to PHP, are keys inherent to arrays? In other words, if I get data from a form that gives me a set of values in the $_POST array, are there keys assigned to the values by default, or do keys only exist if they are created explicitly? I am assuming there are no keys if I don't create them, but I suspect that there could be numerical keys assigned to each value automatically.
In the most basic sense - "key" is just an instruction for computer how to find required value in the array. So key is like an address of value cell. And you don't find a house in a city without an address - so you will likely don't find value in the array without a key either. Most programming languages supports plain arrays, where key is just an integer - 0,1,2,3,... Consider this array's element layout in memory:
Element index/key: 0 1 2 3 4
Value: A B C D E
And when you ask for a computer - give me array[3] element - it knows that
it needs to look at memory cell array_byte_offset_in_ram + size_in_bytes_of(array_element) * 3
Same instruction expressed in human language will be "find where first array element is stored in memory and jump from it forward in memory by 3x memory amount which is needed to store 1 array element". By doing this algo finds your cell and fetches your value D.
For arrays of arbitrary keys, when key can be any string - is another story. But idea remains the same - from the key computer should deduce How to find required element cell in memory. Usually this done by translating arbitrary string keys into integer hash values. Then sorting these hashes and performing binary search algorithm to find integer-index of required hash value. Last step is to pass index found into another plain array where your real values are stored.
Consider this array:
Element key: 'ABC' 'EFG' 'CDE'
Value: a b c
There are many ways to calculate hashes, but for simplicity consider stupid hash function
hash(string) = sum(ascii_values_of_chars_in_string)
So we have following hash table:
hash('ABC') = ord('A')+ord('B')+ord('C')
hash('EFG') = ord('E')+ord('F')+ord('G')
hash('CDE') = ord('C')+ord('D')+ord('E')
After sorting hashes we generate and save such hash array:
hash[0] = 198
hash[1] = 204
hash[2] = 210
Now we can save array values into another plain array where integer index should be the same as hash array index of saved hash(key) function output =>
value[0] = 'a'
value[1] = 'c'
value[2] = 'b'
Now when you request - give me array['EFG'] value - computer calculates key 'EFG' hash which is 210. Then by employing binary search algo finds 210 value in hash table and deduces that it's index in hash table is 2. So it jumps to value table at index 2 by using above described technique of plain arrays and fetches resulting value of 'b' which will be returned to you.
These are the main principles of array keys. Of course there are much more things under the hood - such as hash collisions and etc. But at this point you don't need more complexities as for now. Simply keep in mind that at most bare-bones of computer architecture - there is only plain numbers and math operating on them - no fancy things like "strings"/"objects" and another cosmos :-)
If you assign an existing array to a new variable, it will be like you copied that array to that variable.
So let's say you have:
$initialArray = ["test1" => "My First Test", "test2" => "My Second Test"];
If you initialize a new variable and say it should be equal to the array you desire:
$aNewArray = $initialArray;
Your new array will be exactly like the one you said for it to copy;
Also, if you change $initialArray after you copied to the $aNewArray, your changes will only affect the variable you change, keeping your $aNewArray with the same data before you changed.
Now, if you just set a few variables into an array without specifying keys to access them, it will automatically link them by numeric index:
$arrayWithoutSpecificKeys = ["one", "two", "three"];
print_r($arrayWithoutSpecificKeys);
This output will be:
array (
0 => "one",
1 => "two",
2 => "three"
);
Never forget array start with index 0;
This means if you assign $_POST to a variable, it will inherit the key => values transmitted.
In your form you will name you inputs like this:
<input type="text" name="surname" .../>
Your $_POST variable will have an array with whatever information you set in your input, and link them as bellow:
["surname" => "<your typed value>"]
Then again, if you copy the $_POST to a variable, that variable will inherit all the content that $_POST contains;
Hope it helped!
An array in PHP is actually an ordered map. A map is a type that
associates values to keys.
PHP Documentation
This means that you can only have one index, however you need to be aware that arrays implement an internal pointer, and technically you can iterate the array by sequentially hopping through each array entry. This is what foreach does for you. You can check next documentation for more details.
In case if you don't supply keys when creating an array, then keys will be assigned automatically. Array created by the following line of code will assign index (key) for each of its elements (starting from 0):
$array = array("foo", "bar", "hello", "world");
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
I am someone who has been trying out webdesign for around 2 months now and I have a question. So I have the following array with object:
array(1) {
[0]=>
object(WP_Post)#416 (24) {
["ID"]=>
int(36)
["post_title"]=>
string(7) "Bakuman"
}
I am trying to get the value of "ID", but am not sure how to go about referencing it.
I have tried [0]["ID"], but doesn't work.
Also: Is it possible to get the ID without mentioning the #416 number?
Tried searching for answer, but keep coming up with results that have large amounts of OOP with so much info I can't filter through to what I need. Can anyone hlpe me out?
PHP uses -> for object properties.
So in your case
echo $array[0]->ID;
should output 36
where [0] is the first element of $array which contains the WP_Post object and ID is the property containing the value you're looking for
The 0th element of your array is in fact an object, so to access its properties, you need to use the object referencing operator ->.
Try this: $array[0]->ID
I am working with migration and I am migrating taxonomy terms that the document has been tagged with. The terms are in the document are separated by commas. so far I have managed to separate each term and place it into an array like so:
public function prepareRow($row) {
$terms = explode(",", $row->np_tax_terms);
foreach ($terms as $key => $value) {
$terms[$key] = trim($value);
}
var_dump($terms);
exit;
}
This gives me the following result when I dump it in the terminal:
array(2) {
[0]=>
string(7) "Smoking"
[1]=>
string(23) "Not Smoking"
}
Now I have two fields field_one and field_two and I want to place the value 0 of the array into field_one and value 1 into field_two
e.g
field_one=[0]$terms;
I know this isn't correct and I'm not sure how to do this part. Any suggestions on how to do this please?
If you are only looking to store the string value of the taxonomy term into a different field of a node, then the following code should do the trick:
$node->field_one['und'][0]['value'] = $terms[0];
$node->field_two['und'][0]['value'] = $terms[1];
node_save($node);
Note you will need to load the node first, if you need help with that, comment here and will update my answer.
You are asking specifically about ArrayList and HashMap, but I think to fully understand what is going on you have to understand the Collections framework. So an ArrayList implements the List interface and a HashMap implements the Map interface.
List:
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Map:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
So as other answers have discussed, the list interface (ArrayList) is an ordered collection of objects that you access using an index, much like an array (well in the case of ArrayList, as the name suggests, it is just an array in the background, but a lot of the details of dealing with the array are handled for you). You would use an ArrayList when you want to keep things in sorted order (the order they are added, or indeed the position within the list that you specify when you add the object).
A Map on the other hand takes one object and uses that as a key (index) to another object (the value). So lets say you have objects which have unique IDs, and you know you are going to want to access these objects by ID at some point, the Map will make this very easy on you (and quicker/more efficient). The HashMap implementation uses the hash value of the key object to locate where it is stored, so there is no guarentee of the order of the values anymore.
You might like to try:
list($field_one, $field_two) = prepareRow($row);
The list function maps entries in an array (in order) to the variables passed by reference.
This is a little fragile, but should work so long as you know you'll have at least two items in your prepareRow result.
This is a deeper dive into a previous question I had here: Can items in PHP associative arrays not be accessed numerically (i.e. by index)?
According to W3Schools, :
In PHP, there are three kind of
arrays:
Numeric array - An array with a numeric index
Associative array - An array where each ID key is associated with a value
Multidimensional array - An array containing one or more arrays
But is this accurate? Each element in the array can be assigned either an index or a string as a key- so what happens when the two are mixed in the same array?
$myArray[0] = 'value1';
$myArray['one'] = 'value2';
All arrays in PHP are the same; they're implemented as hash maps which associate keys to values, whatever type the keys may be.
Manual:
The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.
If an array had both numeric and non-numeric indices, though, I'd still call it an associative array. The meaning of "associative" still stands.
Wikipedia:
An associative array is an abstract data type composed of a collection of unique keys and a collection of values, where each key is associated with one value (or set of values).
...
From the perspective of a computer programmer, an associative array can be viewed as a generalization of an array. While a regular array maps an integer key (index) to a value of arbitrary data type, an associative array's keys can also be arbitrarily typed. In some programming languages, such as Python, the keys of an associative array do not even need to be of the same type.
For the last sentence, the same applies for PHP, as shown in your example.
PHP doesn't really have arrays. They are dictionaries. Numeric keys are allowed at the same time as string keys. They can be mixed and do coexist.
(Actually string keys like "123" are always treated as integers. PHP does not keep the type information for them.)
If you want a different behaviour you could implement and extend ArrayObject however. And it would be possible to implement a map, where numeric keys functioned as alias to string indexes.
In general, you should read the official documentation rather than W3Schools.
An array can contain whatever members it wants with whatever keys it wants.
The description provided by W3Schools is quite ambiguous, or even wrong.
Numeric array - An array with a numeric index
I'd say a numeric array is an array with only integer indexes. An array with one I'd probably call a mixed (or associative, see below) array, if I had to call it anything.
Associative array - An array where each ID key is associated with a value.
I don't know about that description. I'd say an array can be associative if it maps strings to values instead of numerical indexes.
Multidimensional array - An array containing one or more arraysNumeric array - An array with a numeric index
An associative array can contain arrays too, which makes it multidimensional.
Keep in mind that an array with all numeric keys (even if in a string) will always be treated as a numeric array. This can mean different things in different contexts.
$arr = array(
'1' => 'abc',
2 => 'def'
);
var_dump($arr);
Output
array(2) {
[1]=>
string(3) "abc"
[2]=>
string(3) "def"
}
You get an associative array. Try this code:
$myArray[0] = 'value1';
$myArray['one'] = 'value2';
echo($myArray[1]);
See? It doesn't echo anything.
Something inportant to note about a PHP well ordered numerical array versus a un-ordered numerical PHP array where the order is not respected (3, 1, 2, 0 instead of 0, 1, 2, 3 ...) is when you are working with an API returning JSON payloads. On the client side, e.g a client written in Javascript, and if you're expecting an array and not an object you could have some difficulties. That's why sometime, on the PHP side, you can see something as follows being returned :
return array_values($array);