Is there a faster way to add all the numbers in each segment of the multidimensional array rather than just doing it all manually? I was told before that a foreach loop could be used but I've hit a brick wall.
I'm trying to make it so it shows the total number of course enrollments in each campus and then the total number of students taking each course.
I feel like the answer is staring me in the face but I'm unsure.
<?
$campus = array();
$campus[1]['course1'] = 5; // <---- Number enrolled
$campus[1]['course2'] = 15;
$campus[1]['course3'] = 22;
$campus[1]['course4'] = 21;
$campus[1]['course5'] = 12;
$campus[1]['course6'] = 25;
$campus[1]['course7'] = 16;
$campus[1]['course8'] = 11;
$campus[1]['course9'] = 17;
$campus[1]['course10'] = 23;
$campus[2]['course1'] = 11;
$campus[2]['course2'] = 23;
$campus[2]['course3'] = 51;
$campus[2]['course4'] = 25;
$campus[2]['course5'] = 32;
$campus[2]['course6'] = 35;
$campus[2]['course7'] = 32;
$campus[2]['course8'] = 52;
$campus[2]['course9'] = 25;
$campus[2]['course10'] = 21;
$campus[3]['course1'] = 2;
$campus[3]['course2'] = 12;
$campus[3]['course3'] = 32;
$campus[3]['course4'] = 32;
$campus[3]['course5'] = 25;
$campus[3]['course6'] = 26;
$campus[3]['course7'] = 29;
$campus[3]['course8'] = 12;
$campus[3]['course9'] = 15;
$campus[3]['course10'] = 11;
echo "<pre>";
print_r($campus);
echo "<br/>";
foreach($campus as $key=>$value)
{
}
Use array_sum() to add the numbers in an array, and use array_map() to apply it to each element of the $campus array.
$total_by_campus = array_map('array_sum', $campus);
$courses = array();
foreach($campus as $key=>$value)
{
foreach($value as $course=>$num)
$courses[$course] += $num;
}
var_dump($courses);
Should do it.
You can use PHP's array_sum() function that will add up the values of the array you give it.
<?php
$sum = array_sum($campus[1]);
echo $sum;
$totcount = 0;
$count = array();
foreach($campus as $key=>$value)
{
foreach($value as $value1 => $value2)
{
$count[$value1]+=$value2;
$totcount++;
}
}
print_r($count);
echo "<br><br><br>". $totcount;
take a look:
$campus = array
(
'1' => array
(
'course1' => 5,
'course2' => 15,
'course3' => 22,
'course4' => 21,
'course5' => 12,
'course6' => 25,
'course7' => 16,
'course8' => 11,
'course9' => 17,
'course10' => 23,
),
'2' => array
(
'course1' => 11,
'course2' => 23,
'course3' => 51,
'course4' => 25,
'course5' => 32,
'course6' => 35,
'course7' => 32,
'course8' => 52,
'course9' => 25,
'course10' => 21,
),
'3' => array
(
'course1' => 2,
'course2' => 12,
'course3' => 32,
'course4' => 32,
'course5' => 25,
'course6' => 26,
'course7' => 29,
'course8' => 12,
'course9' => 15,
'course10' => 11,
),
);
foreach ($campus as $key0 => $value0)
{
// $key0 == (1, 2, 3)
// $value0 == array(course1 => 5, course2 => 15, course3 => 22, ...)
foreach ($value0 as $key1 => $value1)
{
// $key1 == (course1, course2, course3, ...)
// $value1 == (5, 15, 22, ...)
}
}
Sorry, but you post a question: "How to check an array's contents to see if they have any numbers?"
<?php
$cowboyfile = "COWBOY.TXT";
$data = array();
$data[] = "Colt Peacemaker, 12.20";
$data[] = "Holster, 2.00";
$data[] = "Levi Strauss Jeans, 1.35";
$data[] = "Saddle, 40.00";
$data[] = "Stetson, 10.00";
// Writing in the File
file_put_contents($cowboyfile, implode("\r\n", $data));
// Displaying all items above $10
$items = file($cowboyfile);
$item_filtred = array();
for ($i = 0; $i < count($items); $i++)
{
$item = $items[$i];
$item_price = substr($items[$i], strpos($item, ',') + 1);
if ($item_price >= 10)
{
$item_filtred[] = $item;
}
}
print_r($item_filtred);
Related
I need to get the closest lowest and highest to a number.
Attempt
<?php
$a = array(1, 8, 23,42,47, 52, 55, 66, 74,75, 76,77,78, 95,);
sort($a);
$v = 58;
$lesser = null;
$greater = null;
foreach($a as $key => $current){
if($current <= $v){
$lesser = $current;
$greater = $a[($key+1)];
}else{
}
}
print_r(array(
"lesser" => $lesser,
"greater" => $greater,
));
?>
/** output :
Array
(
lesser => 55
greater => 66
)
**/
My aim is to get all the numbers greater to the given number, and the same with the lesser:
greater => 66, 74, 75, 77, 78, 95
lesser => 55, 52, 47, 42, 23, 8, 1
How do I solve this problem?
Make $lesser and $greater arrays that you push onto, instead of replacing.
<?php
$a = array(1, 8, 23,42,47, 52, 55, 66, 74,75, 76,77,78, 95,);
$v = 58;
$lesser = [];
$greater = [];
foreach($a as $key => $current){
if ($current < $v) {
$lesser[] = $current;
} elseif ($current > $v) {
$greater[] = $current;
}
}
print_r(array(
"lesser" => $lesser,
"greater" => $greater,
));
?>
I have an array like the following:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1005, "id_user" => 5));
So it means 5 => 1004, 1005 and 4 => 1000, 1001, 1003 and 3 => 1002.
First, how do I get this structure? (possible with commas)
My algorithm for this solution would be something like (here's what I'm asking you guys..how to accomplish this):
$arr = array();
for($i = 0; $i <= count($content) - 1; $i++){
if exists key ($content[$i]['id_user']) IN $arr then
$arr = add_to_existing_key "," . $content[$i]['id_post']
} other wise {
$arr = add_new_key PLUS value $content[$i]['id_user'] <=> $content[$i]['id_post']
}
}
I need the commas so I could parse the info later.
Basically, the objective of this is to do a loop with $arr variable. Imagining that the array would have, finally, something like:
("id_user" => 5, "ids" => '1004,1005'),
("id_user" => 4, "ids" => '1000,1001,1003'),
("id_user" => 3, "ids" => '1002')
for($i = 0; $i <= count($arr) - 1; $i++){
$ids = explode(",", $arr[$i]['ids']);
$info = array();
for($y = 0; $y <= count($ids) - 1; $y++){
$query->("SELECT * FROM table WHERE id = $ids[$y]");
$info[] = array($name, $description);
}
$email->sendEmail($info); // id = 5 => info OF 1004, 1005
$info = array(); // clear array
// loop
// id = 4 => info OF 1000, 1001, 1003
// loop etc
}
Try this:
$arr = array();
// Loop through each content
foreach ($content as $post)
{
$arr[$post['id_user']][] = $post['id_post'];
}
This way, the result would be
$arr = array(
'5'=> array('1004', '1005'),
'4'=> array('1000', '1001', '1003'),
'3'=> array('1002')
);
Then you won't need to use "explode" just to split those comma-separated IDs
Also
I think you might be better off sticking with arrays instead of joining on commas and then exploding later:
foreach($content as $values) {
if(!isset($result[$values['id_user']])) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
print_r($result);
May be this variant will be exactly what you need:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1005, "id_user" => 5));
// Make preparation array
foreach ( $content as $values ) {
if ( !isset($result[$values['id_user']]) ) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
// Sort inner arrays
foreach ( $result as $key => $valueArray ) {
asort($result[$key]);
}
// Implode arrays to strings
array_walk($result, function(&$array, $key) {
$array = implode(',', $array);
});
// Final array
$result1 = array();
foreach ( $result as $userID => $idsString ) {
$result1[] = array("id_user" => $userID, "id_post" => $idsString);
}
print_r($result1);
My function search inside a multi dimensional array for a match. It works but I would like to know if there is a better way to do that.
$arrays = array(
array('id' => 1, 'color_id' => 2, 'store_id' => 1),
array('id' => 1, 'color_id' => 2, 'store_id' => 2),
array('id' => 2, 'color_id' => 3, 'store_id' => 1)
);
function query_array($array, $keys = array(), $values = array()){
$match = array();
for($i = 0; $i < count($array); $i++){
for($x = 0; $x < count($keys); $x++){
if($array[$i][$keys[$x]] == $values[$x]){
$match[$i][] = 'increment';
if(count($match[$i]) == count($keys)){
return $array[$i];
}
}
}
}
return $match;
}
$searchKeys = array('item_id', 'store_id');
$searchValues = array(2,1);
$match = query_array($arrays, $searchKeys, $searchValues);
echo '<pre>';
print_r($match);
echo '<pre>';
I have an array like this:
array (0 =>
array (
'id' => '20110209172713',
'Date' => '2011-02-09',
'Weight' => '200',
),
1 =>
array (
'id' => '20110209172747',
'Date' => '2011-02-09',
'Weight' => '180',
),
2 =>
array (
'id' => '20110209172827',
'Date' => '2011-02-09',
'Weight' => '175',
),
3 =>
array (
'id' => '20110211204433',
'Date' => '2011-02-11',
'Weight' => '195',
),
)
I need to extract minimal and maximal Weight values.
In this example
$min_value = 175
$max_value = 200
Any help on how to do this ?
Thank you !
Option 1. First you map the array to get those numbers (and not the full details):
$numbers = array_column($array, 'weight')
Then you get the min and max:
$min = min($numbers);
$max = max($numbers);
Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map:
$numbers = array_map(function($details) {
return $details['Weight'];
}, $array);
Option 3.
Option 4. If you only need a min OR max, array_reduce() might be faster:
$min = array_reduce($array, function($min, $details) {
return min($min, $details['weight']);
}, PHP_INT_MAX);
This does more min()s, but they're very fast. The PHP_INT_MAX is to start with a high, and get lower and lower. You could do the same for $max, but you'd start at 0, or -PHP_INT_MAX.
foreach ($array as $k => $v) {
$tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);
For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.
How to get a max value:
$highest_weight = max(array_column($details, 'Weight'));
How to get the min value
$lowest_weight = min(array_column($details, 'Weight'));
It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.
The problem of finding min and max can easily be solved with just two extra memory slots
$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;
foreach($input as $data) {
$weight = intval($data['Weight']);
if($weight <= $min ) {
$min = $weight ;
}
if($weight > $max ) {
$max = $weight ;
}
}
echo " min = $min and max = $max \n " ;
How about without using predefined functions like min or max ?
//find max
$arr = [4,5,6,1];
$val = $arr[0];
$n = count($arr);
for($i=0;$i<$n;$i++) {
if($val < $arr[$i]) {
$val = $arr[$i];
}
}
echo $val;
//find min
$arr = [4,5,6,1];
$val = $arr[0];
$n = count($arr);
for($i=0;$i<$n;$i++) {
if($val > $arr[$i]) {
$val = $arr[$i];
}
}
echo $val;
$num = array (0 => array ('id' => '20110209172713', 'Date' => '2011-02-09', 'Weight' => '200'),
1 => array ('id' => '20110209172747', 'Date' => '2011-02-09', 'Weight' => '180'),
2 => array ('id' => '20110209172827', 'Date' => '2011-02-09', 'Weight' => '175'),
3 => array ('id' => '20110211204433', 'Date' => '2011-02-11', 'Weight' => '195'));
foreach($num as $key => $val)
{
$weight[] = $val['Weight'];
}
echo max($weight);
echo min($weight);
<?php
$array = array (0 =>
array (
'id' => '20110209172713',
'Date' => '2011-02-09',
'Weight' => '200',
),
1 =>
array (
'id' => '20110209172747',
'Date' => '2011-02-09',
'Weight' => '180',
),
2 =>
array (
'id' => '20110209172827',
'Date' => '2011-02-09',
'Weight' => '175',
),
3 =>
array (
'id' => '20110211204433',
'Date' => '2011-02-11',
'Weight' => '195',
),
);
foreach ($array as $key => $value) {
$result[$key] = $value['Weight'];
}
$min = min($result);
$max = max($result);
echo " The array in Minnumum number :".$min."<br/>";
echo " The array in Maximum number :".$max."<br/>";
?>
$Location_Category_array = array(5,50,7,6,1,7,7,30,50,50,50,40,50,9,9,11,2,2,2,2,2,11,21,21,1,12,1,5);
asort($Location_Category_array);
$count=array_count_values($Location_Category_array);//Counts the values in the array, returns associatve array
print_r($count);
$maxsize = 0;
$maxvalue = 0;
foreach($count as $a=>$y){
echo "<br/>".$a."=".$y;
if($y>=$maxvalue){
$maxvalue = $y;
if($a>$maxsize){
$maxsize = $a;
}
}
}
echo "<br/>max = ".$maxsize;
print fast five maximum and minimum number from array without use of sorting array in php
:-
<?php
$array = explode(',',"78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73");
$t=0;
$l=count($array);
foreach($array as $v)
{
$t += $v;
}
$avg= $t/$l;
echo "average Temperature is : ".$avg." ";
echo "<br>List of seven highest temperatsures :-";
$m[0]= max($array);
for($i=1; $i <7 ; $i++)
{
$m[$i]=max(array_diff($array,$m));
}
foreach ($m as $key => $value) {
echo " ".$value;
}
echo "<br> List of seven lowest temperatures : ";
$mi[0]= min($array);
for($i=1; $i <7 ; $i++)
{
$mi[$i]=min(array_diff($array,$mi));
}
foreach ($mi as $key => $value) {
echo " ".$value;
}
?>
I have an array something like this..
[0] => english
[1] => 85
[2] => mathematics
[3] => 75
[4] => science
[5] => 71
[6] => social
[7] => 92
I want all values with even indexes to go as keys and all values odd indexes to go values. Like this
[english] => 85,
[mathematics] => 75
[science] => 71
[social] => 92
Is there any good function to achieve this ? or can you help me with the code ?
A simple loop will do this:
$input = array(
'english',
85,
'mathematics',
75,
'science',
71,
'social',
92,
);
$output = array();
for ($i=0; $i<count($input); $i+=2) {
$output[$input[$i]] = $input[$i+1];
}
print_r($output);
Note: the above code assumes there are an even number of elements.
Something like this:
<?php
$arr[0] = 'english';
$arr[1] = 85;
$arr[2] = 'mathematics';
$arr[3] = 75;
$arr[4] = 'science';
$arr[5] = 71;
$arr[6] = 'social';
$arr[7] = 92;
for($i=0;$i<count($arr);$i++)
{
if($i & 1)
$odd[] = $arr[$i];
else
$even[] = $arr[$i];
}
$result = array_combine($even,$odd);
var_dump($result);
?>
Output:
array(4) {
["english"]=>
int(85)
["mathematics"]=>
int(75)
["science"]=>
int(71)
["social"]=>
int(92)
}
Solution using array_chunk function
$arr = array('english', 85,
'mathematics', 75,
'science', 71,
'social', 92
);
$result = array();
$chunks = array_chunk($arr, 2);
foreach ($chunks as $value) {
$result[$value[0]] = $value[1];
}
In functional style just for the kick (not considering performance):
$odd = function($value) {
return($value & 1);
};
$even = function($value) {
return(!($value & 1));
};
$oddArr = array_filter($arr, $odd));
$evenArr = array_filter($arr, $even));
$ans = array_combine($oddArr,$evenArr);