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).
Related
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
I want to sort an associative array and there is an inbuilt function to achieve the same viz. arsort(), but the problem with this function is that it doesn't maintain the original key order when values are same.
e.g.
$l = [
'a' => 1,
'b' => 2,
'c' => 2,
'd' => 4,
'e' => 5,
'f' => 5
];
The result which I want is :
$l = [
'e' => 5,
'f' => 5,
'd' => 4,
'b' => 2,
'c' => 2,
'a' => 1
];
arsort() gives the result in descending order but it randomly arranges the element when values are same.
This question is not a duplicate of PHP array multiple sort - by value then by key?. In that question it is asking for same numeric value to be sorted alphabetically but in my question I am asking values to sorted according to the original order if they are same.
There is probably a more efficient way to do this, but I think this should work to maintain the original key order within groups of the same value. I'll start with this array for example:
$l = [ 'a' => 1, 'b' => 2, 'c' => 2, 'd' => 4, 'g' => 5, 'e' => 5, 'f' => 5 ];
Group the array by value:
foreach ($l as $k => $v) {
$groups[$v][] = $k;
}
Because the foreach loop reads the array sequentially, the keys will be inserted in their respective groups in the correct order, and this will yield:
[1 => ['a'], 2 => ['b', 'c'], 4 => ['d'], 5 => ['g', 'e', 'f'] ];
sort the groups in descending order by key:
krsort($groups);
Reassemble the sorted array from the grouped array with a nested loop:
foreach ($groups as $value => $group) {
foreach ($group as $key) {
$sorted[$key] = $value;
}
}
You can use array_multisort. The function can be a bit confusing, and really hard to explain, but it orders multiple arrays, and the first array provided gets sorted based on the order of subsequent arrays.
Try:
array_multisort($l, SORT_DESC, array_keys($l));
See the example here: https://3v4l.org/oV8Od
It sorts the array by values descending, then is updated by the sort on the keys of the array.
So I have two array, the first one is like:
$MyArray = [
['id' => 1, number => 32],
['id' => 2, number => 4]
];
and the other is like:
$OtherArray = [
['id' => 1, 'show' => X],
['id' => 5, 'show' => X]
];
Where is X, I want it to be equal with the 'number' value of $MyArray where key 'id' = its id.
If there is no $MyArray.id which is equal to $OtherArray.id then it should return 0.
I hope you understand what I mean. I tried everything, what I could, yet, with no success.
Have you tried using a foreach loop here?
Here is a quick example... PHPaste Snippet
<?php
$firstArray = array(
array(
"id" => 1,
"something" => "Hello, World!"
),
array(
"id" => 3, // 3 on purpose
"something" => "Hello, mom?"
)
);
$secondArray = array(
array(
"id" => 1,
"thing" => null
),
array(
"id" => 2,
"thing" => null
)
);
foreach ($firstArray as $key => $value) {
foreach ($secondArray as $k => $v) {
if ($value['id'] == $v['id']) {
echo "Found one!\n------\n" . print_r($value, true) . "\ncontains the same ID as\n\n" . print_r($v, true) . "\n------\n";
// you may also do this if you want
// $secondArray[$k]['thing'] = $value['id'];
// this would set "thing" (in the second array) to the value of "id" (in the first array)
}
}
}
EDIT Here is a second example, displaying how you could use it as a function... PHPaste Snippet.
Note: I used the OLD array syntax because it's easier for new programmers to understand.
So, essentially what you are doing is iterating through each item in $firstArray, comparing it to each item in $secondArray, by doing a nested foreach within side the first foreach if that makes sense...?
Here is what I just said in simple form:
go through each item in array 1
--> compare it to each item in array 2
You may also notice my use of PHP's lovely function, print_r(). This displays objects and arrays in a slightly, clearer, form.
You can also see that I am getting the values from within the arrays by using $value['id'] and $v['id']. These were defined in my foreach declaration, foreach ($firstArray as $key => $value); $value is an associative array, so you can simply get a value by key just as you would if you created an array like this:
$myArray = [
"id" => 1
];
and grabbed values like this:
echo $myArray['id']; // 1
Hopefully this helped.
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/>';
}
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")
);
?>