Process every two elements in a flat array - php

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);

Related

How to push with a regularity elements in an array php

I have an array of posts ids and an array of videos ids. I need to mix both to have something like "First is a video, then 3 normal posts then another video then 5 normal posts.. repeat... until the end. (ie : Video,normal,normal,normal,Video,normal*5 and repeat..)
My code works but how can i make it more clean and concise ?
$a1 = $video_posts_arr;
$a2 = $standard_posts_arr;
$res = [];
$tc1 = count($a1);
$tc2 = count($a2);
$tc = $tc1 + $tc2;
$i1 = 0;
$i2 = 0;
for ($i = 0; $i < $tc; $i++) {
// first video
if (isset( $a1[$i1] )) {
array_push($res,$a1[$i1]);
$i1++;
}
// next 3 normals
if (isset( $a2[$i2]) ) {
array_push($res,$a2[$i2]);
$i2++;
array_push($res,$a2[$i2]);
$i2++;
array_push($res,$a2[$i2]);
$i2++;
}
// next video
if (isset( $a1[$i1] )) {
array_push($res,$a1[$i1]);
$i1++;
}
// next 5 normals
if (isset( $a2[$i2]) ) {
array_push($res,$a2[$i2]);
$i2++;
array_push($res,$a2[$i2]);
$i2++;
array_push($res,$a2[$i2]);
$i2++;
array_push($res,$a2[$i2]);
$i2++;
array_push($res,$a2[$i2]);
$i2++;
}
}```
It's kind of hard to tell from your wording, but I'm assuming you're wanting to go back and forth between 3 "regular" posts, then 5, then 3, etc, between each "video" post. So as we loop through the video posts, we have to toggle back and forth between those options, and then use that plus a marker/counter to know where to insert each video post in the list of regular posts.
$a1 = array("v1", "v2", "v3", "v4", "v5");
$a2 = array("p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9", "p10", "p11", "p12", "p13", "p14", "p15", "p16");
$skipNum = 3;
$currentPos = 1;
array_unshift($a2, array_shift($a1));
foreach($a1 as $v)
{
$currentPos+= $skipNum;
array_splice($a2, $currentPos, 0, $v);
$currentPos++;
if($skipNum == 3)
{
$skipNum = 5;
}
else
{
$skipNum = 3;
}
}
var_dump($a2);
DEMO
how can i make it more clean and concise ?
Here's what I think you should do...
Iterate on the video array and inject each video element into the standard post array at the variable positions without making any replacements.
Code: (Demo)
$video_posts_arr = range('a','e');
$standard_posts_arr = range(1, 16);
$pos = 0;
foreach ($video_posts_arr as $index => $video) {
array_splice($standard_posts_arr, $index + $pos, 0, $video);
$pos += $index & 1 ? 5 : 3;
}
var_export($standard_posts_arr);
Using the $index of the videos array spares having to use incrementation while iterating.
I am using a ternary expression with a bitwise condition to increase the $pos based on whether $index is odd. I should express these variables to better explain what is happening. As shown in this Demo, these are the values generated as $index increases:
$index = 0, $pos = 0; splicePoint = 0, isOdd = false
$index = 1, $pos = 3; splicePoint = 4, isOdd = true
$index = 2, $pos = 8; splicePoint = 10, isOdd = false
$index = 3, $pos = 11; splicePoint = 14, isOdd = true
$index = 4, $pos = 16; splicePoint = 20, isOdd = false
Output:
array (
0 => 'a',
1 => 1,
2 => 2,
3 => 3,
4 => 'b',
5 => 4,
6 => 5,
7 => 6,
8 => 7,
9 => 8,
10 => 'c',
11 => 9,
12 => 10,
13 => 11,
14 => 'd',
15 => 12,
16 => 13,
17 => 14,
18 => 15,
19 => 16,
20 => 'e',
)
The above script is demonstrated using a ratio of videos to standard posts which results in no consecutive videos.
If your video to standard post ratio is too great, then the above script will simply append all remaining/extra videos to the end of the standard posts array.
If you would like to ensure that the final element in your standard posts array is not a video, then you can add a conditional break like this:
$pos = 0;
foreach ($video_posts_arr as $index => $video) {
$injection_pos = $index + $pos;
if (!isset($standard_posts_arr[$injection_pos])) {
break;
}
array_splice($standard_posts_arr, $injection_pos, 0, $video);
$pos += $index & 1 ? 5 : 3;
}
Or to allow a maximum of one video after the last standard post, move the break after the array_splice() call and account for the injected video element like this:
$pos = 0;
foreach ($video_posts_arr as $index => $video) {
$injection_pos = $index + $pos;
array_splice($standard_posts_arr, $injection_pos, 0, $video);
if (!isset($standard_posts_arr[$injection_pos + 1])) {
break;
}
$pos += $index & 1 ? 5 : 3;
}
Maybe something like that?
This solution uses array_merge and array_slice to create result. This methods does not edit original arrays, just creates new one based on arguments.
$a1 = array("v1", "v2", "v3");
$a2 = array("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10");
$output = array_merge(
array_slice($a1, 0, 1), //take one arg from a1. Not smartest to be honest but works. Maybe someone will give better idea here.
array_slice($a2, 0, 3), //take first 3 elements from a2
array_slice($a1, 1, 1),
array_slice($a2, 3, 5),
array_slice($a2, 300, 500), //it is save :)
);
print_r($output);
# [0] => v1
# [1] => a1
# [2] => a2
# [3] => a3
# [4] => v2
# [5] => a4
# [6] => a5
# [7] => a6
# [8] => a7
# [9] => a8
# [10] => a9
# [11] => a10
array_slice that takes only one argument array_slice($a1, 0, 1) looks bit cryptic but at least it is save to use.
This'll create new array instead of editing existing one. It comes with some additional overhead (You probably should not worry about it).
http://sandbox.onlinephpfunctions.com/code/9b23381b31ab7ed48f1941cbca981071eaf250af

Get the combination from other array

I have two array
First
array(
0 => 100000,
1 => 50000,
2 => 100000,
3 => 100000);
Second
array(
0 => 150000,
1 => 200000,);
The problem is I want to get the combination from first array that formed each second array.
Example
Second array index 0 can be formed from first array index 0 and 1 and second array index 1 can be formed from first array index 2 and 3
I want to achieve like this
[0 => [0,1] , 1 => [2,3]]
Thanks for the help.
A simple an fast gready approach would be to first sort the arrays descending. After that, loop over the second one and collect from the first one as much values, till you reach your desired value.
$first = [
0 => 100000,
1 => 50000,
2 => 100000,
3 => 100000
];
$second = [
0 => 150000,
1 => 200000
];
arsort($first);
arsort($second);
$combinations = [];
foreach ($second as $search) {
$combination = [];
$sum = 0;
foreach ($first as $key => $val) {
if ($sum + $val > $search) continue;
$sum += $val;
$combination[] = $key;
if ($sum == $search) break;
}
if ($sum != $search) die("nothing found this way..");
foreach ($combination as $val) unset($first[$val]);
$combinations[] = $combination;
}
print_r($combinations);
Here is the simple idea to achieve your requirement. There would be many if's and but you need to consider yourself
<?php
$arr1 = [0 => 100000,1 => 50000,2 => 100000,3 => 100000];
$arr2 = [0 => 150000,1 => 200000];
//$arr2 = [0 => 250000,1 => 100000];
$count = 0;
$new = array();
for($i=0;$i<count($arr1);$i++){
if($arr1[$i] == $arr2[$count]){
$new[$arr2[$count]] = $arr1[$i];
$count++;
}else{
$sum = [$arr1[$i]];
for($j=$i+1;$j<count($arr1);$j++){
$sum[] = $arr1[$j];
if( array_sum($sum) == $arr2[$count]){
$new[$arr2[$count]] = $sum;
$count++;
}
}
}
}
print_r($new);
?>
Output1
Output2
Try with following code:
$arr = array(
0 => 100000,
1 => 50000,
2 => 100000,
3 => 100000);
$count = $val = 0;
$newArr = [];
foreach($arr as $a){
$val += $a;
$count++;
if($count == 2){
$newArr[] = $val;
$val = $count = 0;
}
}
print_r($newArr); die;

Adding numbers in a multidimensional array

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);

Get min and max value in PHP Array

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;
}
?>

How to insert an element in any position in php

I am with an array like $x = array(1,2,3,4,5); i would like to add element 6 in between 3 and 4 and make it like array(1,2,3,6,4,5);
how do i make it in that place or first place?
array_insert($array,$pos,$val);
function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
Try this:
$x = array(1,2,3,4,5);
$x = array_merge(array_slice($x, 0, 3), array(6), array_slice($x, 3));
print_r($x);
Output;
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 6
[4] => 4
[5] => 5
)
Use array_splice($array, $pos, 0, array($val)).
It can by done like this:
function array_insert_value(array $array = array(), $value = null, $position = null)
{
if(empty($position))
return array_merge($array, array($value));
else
return array_merge(
array_slice($array, 0, $position),
array($value),
array_slice($array, $position)
);
}
I cam up with this function. I have also included the code I used for testing I hope this helps.
function chngNdx($array,$ndex,$val){
$aCount = count($array);
for($x=($aCount)-1;$x>=$ndex;$x--){
$array[($x+1)] = $array[$x];
}
$array[$ndex] = $val;
return $array;
}
$aArray = array();
$aArray[0] = 1;
$aArray[1] = 2;
$aArray[2] = 3;
$aArray[3] = 4;
$aArray[4] = 5;
$ndex = 3; // # on the index to change 0-#
$val = 6;
print("before: ".print_r($aArray)."<br />");
$aArray = chngNdx($aArray,$ndex,$val);
print("after: ".print_r($aArray)."<br />");

Categories