I have 2 arrays with some sample data and I just want to confirm if I have the terminology correct:
Multidimensional Array:
$names = array([
"name" => "Bob",
"age" => 25,
"level" => 6],
["name" => "Joe",
"age" => 34,
"level" => 6]
);
Multidimensional Associative Array:
$names = array(
"Bob" => array(
"age" => 25,
"diploma" => "DAC",
"level" => 6),
"Joe" => array(
"age" => 34,
"diploma" => "DAC",
"level" => 6)
);
The second is Associative because of the index being the name rather than an index number and MultiDimensional because it has more than one entry.
I know it is not really a programming question requiring a code solution, I am just learning the terminology.
I add my two cents. All said by others is pretty correct, but:
The main difference from associative arrays and "simple" arrays. With "simple" arrays you can do something like this
for( $i = 0; $i < count( $array ) - 1; $i++ ) {
$element = $array[ $i ];
// Do something with $element
}
With associative arrays, you cannot do it and, if you want to traverse all the arrays you have to do something like this
foreach( $array as $key => $element ) {
// Do something with $element
}
This approach (the foreach) can be applied to the "simple" array too, while the first can be applied ONLY to "simple" array
Multidimensional array are simply arrays with AT LEAST one element that is an array, no matter the "type"
By the way, it's always think about arrays as associative arrays, always. It prevents you some very simple mistakes later on
Both arrays are multidimensional associative array.
But in second array you can get details of Bob or Joe by just using their name as key. For example to get details of Bob you can just call:
$names['Bob']
In first array you have to know the id or index of array to which Bob details were stored.
Related
This question already has an answer here:
array_push won't give an array, prints out integer value
(1 answer)
Closed 4 years ago.
I've attempted many different ways to push an array into a multidimensional array, including array_push(), $array['index'] = $toPush but I keep being met with quite unexpected results. I have used both var_dump() and print_r() as detailed below in an attempt to debug, but cannot work out the issue.
My reasoning behind is to run a while loop to pull game id's and game names and store these in an assoc. array, and then push them into my main array.
$games_array = array
(
"games" => array
(
array("id"=>"1", "game"=>"first game");
array("id"=>"2", "game"=>"second game");
)
);
// a while loop would run here and update $game_to_add;
$game_to_add = array("id"=>"$game['id']", "game"=>"$game['title']");
$games_array = array_push($games_array['games'], $game_to_add);
In this example, the while() would update the ID and the Game inside of $game_to_add
But, whenever I attempt this it simply overwrites the array and outputs an integer ( example: int(3) )
I don't understand what the problem is, any explination would be appreciated as I cannot find a question specifically for this.
My actual test code:
$games_array = array( "games" => array(
array("id" => "1", "name" => "Star feathers"),
array("id" => "2", "name" => "chung fu")
)
);
$another_game = array("id" => "3", "name" => "some kunt");
$games_array = array_push($games_array["games"], array("id" => "3", "name"
=>"some game"));
var_dump($games_array);
You're assigning the return value of array_push to the games array.
The return value of array_push is the amount of elements after pushing.
Just use it as
array_push($array, $newElement);
(Without assignment)
If you're only pushing one element at he time, $array[] = $newElement is preferred to prevent overhead of the function call of array_push
I'm trying to sort following array:
$myArray = array(
"ID" => array(
0,
5,
8,
12,
15
),
"date" => array(
1484391600,
1483910300,
1484920000,
1482393630,
1484391600
),
"name" => array(
"Pete",
"Max",
"Tom",
"June",
"Arend"
),
);
I want to be able to choose which subarray is sorted and in which way (numeric / string) and order (DESC / ASC). All the other subarrays should be sorted accordingly.
Here is some code that worked at first, but when the subarray to sort contained an empty string, it failed: All subarrays where sorted differently.
$sortCatArray = $myArray['name'];
foreach($myArray as $category => $value){
$keepOrigin = $sortCatArray;
array_multisort($keepOrigin, SORT_DESC, SORT_STRING, $myArray[$category]);
}
var_dump($myArray);
Can someone point out what I'm doing wrong.
Also I don't want to rearrange the arrays to match the other sorting solutions as I need the values in the given format.
I have a multidimensional associative array that is made of of animals:
$animals = ["Cat"=>["name"=>"Junior","age"=>16],"Dog"=>["name"=>"Puppy","age"=>"Deceased"]];
I want to add a new animal to it. I know I can do this:
$animals["Lizard"]["name"]="Allen";
$animals["Lizard"]["age"]="Deceased";
But is there a way to do in in one statement, such as
$animals["Lizard"](["name"]="Eric",["age"]=>"Deceased");
Sorry I know this is a really dumb question but I'm a beginner. Thanks.
Just add entire array as an element:
$animals["Lizard"] = [ "name" => "Eric", "age" => "Deceased" ];
or
$animals["Lizard"] = array( "name" => "Eric", "age" => "Deceased" );
Manual (look at example #6).
I'm trying to understand arrays better. Pardon my elementary questions as I just opened my first php book three weeks ago.
I get that you can retrieve key/value pairs using a foreach (or for loop) as below.
$stockprices= array("Google"=>"800", "Apple"=>"400", "Microsoft"=>"4", "RIM"=>"15", "Facebook"=>"30");
foreach ($stockprices as $key =>$price)
What I get confused about are multi dimensional arrays like this one:
$states=(array([0]=>array("capital"=> "Sacramento", "joined_union"=>1850, "population_rank"=> 1),
[1]=>array("capital"=> "Austin", "joined_union"=>1845,"population_rank"=> 2),
[2]=>array("capital"=> "Boston", "joined_union"=>1788,"population_rank"=> 14)
));
My first question is really basic: I know that "capital', "joined_union", "population_rank" are keys and "Sacramento", "1850", "1" are values (correct?). But what do you call [0][1][2]? Are they "main keys" and "capital" etc. sub-keys? I can't find any definition for those; neither in books nor online.
The main question is how do I retrieve Arrays [0][1][2]? Say I want to get the array that joined_union in 1845 (or even trickier during the 1800s), then remove that array.
Finally, can I name Arrays [0][1][2] as California, Texas and Massachusetts correspondingly?
$states=(array("California"=>array("capital"=> "Sacramento", "joined_union"=>1850, "population_rank"=> 1),
"Texas"=>array("capital"=> "Austin", "joined_union"=>1845,"population_rank"=> 2),
"Massachusetts"=>array("capital"=> "Boston", "joined_union"=>1788,"population_rank"=> 14)
));
Unlike other languages, arrays in PHP can use numeric or string keys. You choose.
(This is not a well loved feature of PHP and other languages sneer!)
$states = array(
"California" => array(
"capital" => "Sacramento",
"joined_union" => 1850,
"population_rank" => 1
),
"Texas" => array(
"capital" => "Austin",
"joined_union" => 1845,
"population_rank" => 2
),
"Massachusetts" => array(
"capital" => "Boston",
"joined_union" => 1788,
"population_rank" => 14
)
);
As for querying the structure you have, there are two ways
1) Looping
$joined1850_loop = array();
foreach( $states as $stateName => $stateData ) {
if( $stateData['joined_union'] == 1850 ) {
$joined1850_loop[$stateName] = $stateData;
}
}
print_r( $joined1850_loop );
/*
Array
(
[California] => Array
(
[capital] => Sacramento
[joined_union] => 1850
[population_rank] => 1
)
)
*/
2) Using the array_filter function:
$joined1850 = array_filter(
$states,
function( $state ) {
return $state['joined_union'] == 1850;
}
);
print_r( $joined1850 );
/*
Array
(
[California] => Array
(
[capital] => Sacramento
[joined_union] => 1850
[population_rank] => 1
)
)
*/
-
$joined1800s = array_filter(
$states,
function ( $state ){
return $state['joined_union'] >= 1800 && $state['joined_union'] < 1900;
}
);
print_r( $joined1800s );
/*
Array
(
[California] => Array
(
[capital] => Sacramento
[joined_union] => 1850
[population_rank] => 1
)
[Texas] => Array
(
[capital] => Austin
[joined_union] => 1845
[population_rank] => 2
)
)
*/
1: Multidimensional arrays are basically 'arrays of arrays'.
So if we look here:
array("0"=>array("capital"=> "Sacramento", "joined_union"=>1850, "population_rank"=> 1)
0 is the key, and the array is the value.
Then, inside the value, you have capital as a key, and Sacramento as a value.
2: For removing arrays: Delete an element from an array
3: State names for keys
Yes, you can change that 0, 1, 2 into state names. They become key-values instead of a numbered array. Which makes it much easier to remove exactly the one you want to remove.
Multidimensional arrays are simply arrays which have arrays as values. Simple or "scalar" types are types likes int, string and bool, they hold one value and one value only. Arrays are a compound type, meaning it's a thing that combines several other things together. An array can contain values of other types, including arrays.
The simplest visualization is probably this longhand:
$array = array('foo' => array('bar' => 'baz'));
$foo = $array['foo']; // $foo is now array('bar' => 'baz')
echo $foo['bar']; // outputs 'baz'
This is just shorthand for the same thing as above:
echo $array['foo']['bar'];
$array['foo'] gives you access to the value array('bar' => 'baz'), ['bar'] on that array gives you the value 'baz'. It doesn't matter whether you assign the intermediate value into a variable or continue directly.
The other way around, here's a demonstration of the concept that multidimensional arrays are just arrays in arrays:
$baz = 'baz';
$bar = array('bar' => $baz);
$array = array('foo' => $bar);
That's all there is to it.
You can call nested arrays in array "sub arrays", though there's no real definition and it's not really necessary to define this, since nested arrays aren't a special case of anything.
You may stumble upon explanations using the terms "two dimensional", "three dimensional" etc. arrays. Do not imagine this as tables and cubes, because it's not accurate and will make your head explode when it goes beyond three dimensions. This "dimensionality" simple refers to the depth of the array, i.e. how many arrays are nested within each other.
In php I'm willing to check the existence of indexes that match with another values in array.
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
MY ideal result is, in this case, to get "form" and "date". Any idea?
Try
$fields_keys = array_keys($fields);
$fields_unique = array_diff($fields_keys, $indexes);
The result will be an array of all keys in $fields that are not in $indexes.
You can try this.
<?php
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
$b = array_diff(array_keys($fields), $indexes);
print_r($b);
You can use array_keys function to retrieve keys of a array
Eg:
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
Outputs
Array
(
[0] => 0
[1] => color
)
PHP Documentation
Your question is a little unclear but I think this is what you're going for
array_keys(array_diff_key($fields, array_fill_keys($indexes, null)));
#=> Array( 0=>"form", 1=>"date" )
See it work here on tehplayground.com
array_keys(A) returns the keys of array A as a numerically-indexed array.
array_fill_keys(A, value) populates a new array using array A as keys and sets each key to value
array_diff_key(A,B) returns an array of keys from array A that do not exist in array B.
Edit turns on my answer got more complicated as I understood the original question more. There are better answers on this page, but I still think this is an interesting solution.
There is probably a slicker way than this but it will get you started:
foreach(array_keys($fields) as $field) {
if(!in_array($field, $indexes)) {
$missing[] = $field;
}
}
Now you will have an array that holds form and date.