php multidimensional array - php

I want to create a twodimensional array in php. What is the correct syntax of creating an empty multidimensional array in php.
Secondly I want to create 7 two dimensional array in for

Take a look at the PHP online manual. The first example shows you how to create a multi dimensional array.
http://php.net/manual/en/function.array.php
<?php
$twoDimensionalArray = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
To do what you want in a for loop, you can do so like this
// the following creates a 2d array. the first dimension contains 7 arrays of numbers 1 to 10
$firstDimension = array();
for ($i = 0; $i < 7; $i++) {
$firstDimension[] = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}

Unlike some other langauges (such as standard C), arrays in PHP are "sparse" (i.e.: they only take up the space they need) so you can define a multi-dimensional array simply via:
$testArray = array();
(i.e.: You don't need to reserve the amount of space you're going to require.) However, more usefully, you can add values as follow:
$testArray = array();
$testArray[0][0] = "Hello";
$testArray[0][1] = "World";
...
That said, I'd recommend reading the PHP array manual page, as you might want to use named indexes, etc. and it has better examples.

Multi-dimentional arrays are like regular arrays but the value to some (or all) or their keys are arrays.
For example you can create a two dimentional array like this:
$arr = array();
$arr[1] = array(1 => 'one', 2 => 'two');
And you can use it like this:
echo $arr[1][1]; //which prints "one"

To create empty multidimensional array in PHP, you can do the following.
$arr_1 = array();
Yes. That's all. You can insert any type of data or array in it. There is no specific declaration of various arrays in PHP.
Now, suppose I want to insert data inside this multidimensional array $arr_1. I need to create an array of addresses. Each address item will have city, state and country.
You can do this as follows:
$arr_1[0] = array(
'city' => 'Gurgaon',
'state' => 'Haryana',
'country' => 'India'
);
$arr_1[1] = array(
'city' => 'Los Angeles',
'state' => 'California',
'country' => 'United States'
);
$arr_1[1] = array(
'city' => 'Melbourne',
'state' => 'Victoria',
'country' => 'Australia'
);
You can create as many arrays as you want in this way.
If you want to learn more about PHP arrays (Indexed, Associative, Multidimensional), visit PHP arrays explained with examples - Webolute Blog

<?php
$twoDimensionalArray = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>

Related

how to convert key values of array in php

Hi I am trying to convert the values of an array of grades of students to the alphabetical values and then I wnat to echo them. That is, I am retrieving this array
Array (
'discipline' => 5,
'practicals' => 1,
'presentations' => 2,
'assignments' => 3,
'communication_skills' => 4,
'average' => 3,
'marks' => 25,
'grade' => 'A'
)
and now want to give output as
discipline=>'D',
practicals => A
presentation => B+
assignments=> B
communication_skills => C
Is it possible to do without writing long if than else code in PHP.
If the source of the student is a multidimensional array, then you can loop through the students skipping the overall grade and marks from the array, changing only the subject grades.
If your not using a multidimensional array, you can simply remove the first foreach loop and then change the syntax of variable names to address a single student.
$grades = ['a+', 'a', 'b']; //change accordingly to your grade schema
$students = []; // The source of your student array goes here if it's multidimensional
foreach($students as $student){
foreach($student as $subject => $grade){
if($subject == 'grade' || $subject = 'marks'){
continue;
}
$student[$subject] = $grades[(int)$grade];
}
}
Create an array of grades and then use it to show grades instead of numbers:
<?php
$grades = [
1=>'A',
2=>'B+',
3=>'B',
4=>'C',
5=>'D'
];
$array = [
'discipline' => 5,
'practicals' => 1,
'presentations' => 2,
'assignments' => 3,
'communication_skills' => 4,
'average' => 3,
'marks' => 25,
'grade' => 'A'
];
foreach($array as $key=>$value){
if(!in_array($key, ['average','marks','grade'])){
$array[$key] = $grades[$value];
}
}
print_r($array);
Output: https://3v4l.org/sCWHb
Note:- Used in_array() to skip columns while assigning grades.
It's because if in case more columns needs to be ignored while assigning grades then just add them to the array used inside in_array(). That's it and it will work fine (no other code modification needed).

php Sorting an array based upon key value of another array

I have one array:
$array_sorter = [
'XXS' => 1,
'XS' => 2,
'S' => 3,
'M' => 4,
'L' => 5,
'XL' => 6,
'XXL' => 7
];
and another one that could be like this:
$array_to_sort = ('XS','M','XL','S','L','XXS')
how can I do to sort the second one based upon the first one?
I mean:
$array_to_sort are sizes but they are random inside this array
I need to print the list of available sizes ($array_to_sort) but in the order of $array_sorter
As stated by #Jakumi, usort would be the way to go. However this way might be easier to understand if you are a beginner :
$array_sorter = [
'XXS' => 1,
'XS' => 2,
'S' => 3,
'M' => 4,
'L' => 5,
'XL' => 6,
'XXL' => 7,
];
$array_to_sort = array('XS', 'M', 'XL', 'S', 'L', 'XXS');
$array_sorted = array();
foreach($array_to_sort as $item){
$k = $array_sorter[$item];
$array_sorted[$k] = $item;
}
ksort($array_sorted);
Simply use the first array as a "weight"-provider. I mean the first array have a weight for every entry of your second array (e.g. M get the weight 4).
loop over the second array and create a thrid one: $weightArray like this:
$weightArray = array();
foreach($array_to_sort as $value){
$weight = $array_sorter[$value];
if(!isset($weightArray[$weight])){
$weightArray[$weight] = array();
}
$weightArray[$weight][] = $value;
}
Now you have an array like this: (2=>'XS', 4=>'M', 5=>'XL', 3=>'S', 5=>'L', 1=>'XXS')
now you can sort it by key ksort() and copy it back to your source array like this:
$array_to_sort = array_values(ksort($weightArray));
PS: if you have something like $array_to_sort = ('XS','M','M','M','L','XXS') it will also work => $array_to_sort = ('XXS','XS','M','M','M','L')
Thanks to all for you suggestion
I found alone this solution:
my mistake was focusing on the array to be sorted ($arrat_to_sort)
instead I turned the problem:
as $array_sorter always contains all possible values of $arrat_to_sort
in the right order, I used the function array_intersect($ array_sorter, $ arrat_to_sort)
and immediately I have an array with the values of $ arrat_to_sort in the $array_sorter position

Simple PHP array for storing text?

I'm trying to learn some basic PHP but am running into some confusion around using arrays.
I have three "pools" of words. 20 words in each pool for a total of 60 words.
I need to store these in separate arrays, and then pull out a random selection from the array on click of a button. So each time the button is clicked, another four will be pulled from my array of 20 entries.
You can see my non-functioning page here: http://francesca-designed.me/create-a-status/
So the words on the side, when you click the button it'd run through the 20 words in the array and output them in each span, just four each time you click the button.
I looked on the PHP site and found this but I'm confused about which one to use.
Ultimately I would like to add this to a database as in the end if will be 50 words per pool, but for now I want to keep it all in one place while I practice.
<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
There are two types of arrays:
array(
'key' => 'value',
'key' => 'value',
'key' => 'value',
)
and
array(
'value',
'value',
'value',
'value',
);
the latter is the same as:
array(
0 => 'value',
1 => 'value',
2 => 'value',
3 => 'value',
);
it's really how you want to use them...
if you loop through them with
foreach($array as $value) {
}
or
foreach($array as $key => $value) {
}
and there is no need for named keys, just use the second array.
edit:
$array = array(
'one' => array ('qwe1rty1','qwe1rty2','qwe1rty3'),
'two' => array ('qwe2rty1','qwe2rty2','qwe2rty3'),
'three' => array ('qwe3rty1','qwe3rty2','qwe3ert3'),
);
$array['one'][2] === 'qwe1rty3' (index starts at 0)
$array['three'][0] === 'qwe3rty1'
foreach($array['one'] as $key => $value) {
echo $key .' : ' $value;
}
gives
0 : qwe1rty1
1 : qwe1rty2
2 : qwe1rty3
Here is an example that is similar to what you're describing:
$words = array("tasty", "wretched", "simple", "gnarly", "fruitful", "cleeeever");
echo $words[1]; //prints wretched
for($i=0;$i<4;$i++) {//prints array in original order
echo $words[$i].'<br/>';
}
shuffle($words);
for($i=0;$i<4;$i++) {//prints shuffled array
echo $words[$i].'<br/>';
}

PHP Get minimum value of a key in array of arrays

I have an array like this:
$array = array(
array('id' => 1, 'quantity' => 10),
array('id' => 2, 'quantity' => 25),
array('id' => 3, 'quantity' => 38),
...
);
I want to find the array contains minimum of quantity. How can I do it simply in one two lines of code?! (I prefer to use PHP functions)
Also if the variable is an Object, Does it make any difference?!
Like this:
usort($array,function($a,$b) {return $a['quantity']-$b['quantity'];});
return $array[0];
If needed, create a copy of the original array using $copy = array_slice($array,0);
For the min value:
$min = min(array_map("array_pop",$array));
print_r($min);
For the key:
$min = array_keys(array_map("array_pop",$array), min(array_map("array_pop",$array)));
print_r($min[0]);

array values in multidimensional array

I have two arrays
they look like
$a1 = array(
array('num' => 1, 'name' => 'one'),
array('num' => 2, 'name' => 'two'),
array('num' => 3, 'name' => 'three'),
array('num' => 4, 'name' => 'four'),
array('num' => 5, 'name' => 'five')
)
$a2 = array(3,4,5,6,7,8);
I want to end up with an array that looks like
$a3 = array(3,4,5);
so basically where $a1[$i]['num'] is in $a2
I know I could do
$a3 = array();
foreach($a1 as $num)
if(array_search($num['num'], $a2))
$a3[] = $num['num'];
But that seems like a lot of un-needed iterations.
Is there a better way?
Ah Snap...
I just realized I asked this question the wrong way around, I want to end up with an array that looks like
$a3 array(
array('num' => 3, 'name' => 'three'),
array('num' => 4, 'name' => 'four'),
array('num' => 5, 'name' => 'five')
)
You could extract the relevant informations (the 'num' items) from $a1 :
$a1_bis = array();
foreach ($a1 as $a) {
$a1_bis[] = $a['num'];
}
And, then, use array_intersect() to find what is both in $a1_bis and $a2 :
$result = array_intersect($a1_bis, $a2);
var_dump($result);
Which would get you :
array
2 => int 3
3 => int 4
4 => int 5
With this solution :
you are going through $a1 only once
you trust PHP on using a good algorithm to find the intersection between the two arrays (and/or consider that a function developed in C will probably be faster than any equivalent you could code in pure-PHP)
EDIT after the comment : well, considering the result you want, now, I would go with another approach.
First, I would use array_flip() to flip the $a2 array, to allow faster access to its elements (accessing by key is way faster than finding a value) :
$a2_hash = array_flip($a2); // To speed things up :
// accessing by key is way faster than finding
// an item in an array by value
Then, I would use array_filter() to apply a filter to $a1, keeping the items for which num is in the $a2_hash flipped-array :
$result = array_filter($a1, function ($item) use ($a2_hash) {
if (isset($a2_hash[ $item['num'] ])) {
return true;
}
return false;
});
var_dump($result);
Note : I used an anonymous function, which only exist with PHP >= 5.3 ; if you are using PHP < 5.3, this code can be re-worked to suppress the closure.
With that, I get the array you want :
array
2 =>
array
'num' => int 3
'name' => string 'three' (length=5)
3 =>
array
'num' => int 4
'name' => string 'four' (length=4)
4 =>
array
'num' => int 5
'name' => string 'five' (length=4)
Note the keys are not corresponding to anything useful -- if you want them removed, just use the array_values() function on that $result :
$final_result = array_values($result);
But that's probably not necessary :-)

Categories