I have two arrays array1 and array2. I want to merge these two arrays into one and show the values of merged array in a dropdown. I want the values in a way that the value of first array - value of 2nd array.
e.g:
$employeePlaces1 = array(1, 2, 4,9);
$employeePlaces2 = array(3, 5, 6,7);
I want in dropdown the value as $employeePlaces1[0]-$employeePlaces2[1],
$employeePlaces1[0]-$employeePlaces2[1].
1-3,
2-5,
4-6,
9-7.
How can I do this ?
$employee1 = array(1, 2, 4, 9);
$employee2 = array(3, 5, 6, 7);
function doMerge($n, $m) {
return $n.'-'.$m;
}
$c = array_map("doMerge", $employee1, $employee2);
print_r($c);
Or in PHP 5.3 syntax with lambda style functions:
$c = array_map(function($n, $m) {return $n.'-'.$m;}, $employee1, $employee2);
You can use the array_diff function
http://www.php.net/manual/en/function.array-diff.php
Answer for the edited question
//assuming both the arrays have the same length
echo "<select>";
for($i=0;$i<count($employeePlaces1);$i++)
{
echo "<option>".$employeePlaces1[i]." - ".$employeePlaces2[i]."</option>";
}
echo "</select>";
How about using array_combine?
http://www.php.net/manual/en/function.array-combine.php
Here is how you could manually loop through them and match the values together.
$list = array();
for($i=0; $i<=count($employeePlaces1); $i++) {
$list[] = $employeePlaces1[$i].'-'.$employeePlaces2[$i];
}
Haven't tested, but should be the gist of what you need.
Why not just loop over the arrays, i.e. do it longhand. Then you can get on with something else!
Edit in response to comment 1:
CakePHP is expecting:
<?php echo $this->Form->input('field', array('options' => array(
'Value 1'=>'Label 1',
'Value 2'=>'Label 2',
'Value 3'=>'Label 3'
))); ?>
so something like (pseudocode):
resultsArray = array();
loop
resultsArray[i] = inputArray_1[i]-inputArray_2[i];
endloop
in PHP (assumes size of array1 <= size of array2):
for($i=0;$i<count($inputArray_1);$i++)
{
$resultsArr[$i] = $inputArray_1[$i]-$inputArray_2[$i];
}
Related
I have a code like this:
Lets assume that this arrays has this values:
$arr1 = array();
$arr2 = array();
$result = array();
$arr1[] = array( 'grade' => [1,2,3,4] );
$arr2[] = array( 'grade' => [1,2,3,4] );
foreach($arr1 as $a1){
$set1 = $a1['grade'];
foreach($arr2 as $a2){
$set2 = $a2['grade'];
}
$result[] = array('show_result' => $set1+$set2);
}
foreach{$result as $res){
echo $res['show_result'];
}
The output of the array $res['show_result'] must be:
2, 4, 6, 8
But I get the wrong addition of this arrays. Help will be much appreciated.
As Joni said, your first error is on line 3: ' should be ;
Then, you're not filling arrays like you wanted : array( 'grade' => 1,2,3,4 ); creates an array with first key is 'grade' with value '1', then second key is '0' with value '2' etc...
Your last foreach loop has a syntax error similar to your first error.
See a working correction here
$arr1 = array();
$arr2 = array();
$result = array();
array_push($arr1, 1, 2, 3, 4); //fill array with 4 values (integers)
array_push($arr2, 1, 2, 3, 4); //fill array with 4 values (integers)
//so $arr1 & $arr2 are now a 4 elements arrays
$length = count($arr1); //size of array, here 4
for ($i = 0; $i < $length; $i++) { //loop over arrays
array_push($result, ($arr1[$i] + $arr2[$i])); //fill the results array with sum of the values from the same position
}
var_dump($result);
You have quite a few syntax errors in your code.
Although this solution works, the idea behind using the same counter, $i, to extract a value from both arrays is brittle. For example, you'll get an Undefined offset if the first array has 5 grades instead of 4. If you take a step back and explain your problem in the larger context, perhaps we can provide a better solution. I get the sneaking suspicion you're asking an XY Problem.
http://sandbox.onlinephpfunctions.com/code/bb4f492c183fcde1cf4edd50de7ceebf19fe343a
<?php
$gradeList1 = ['grade' => [1,2,3,4]];
$gradeList2 = ['grade' => [1,2,3,4]];
$result = [];
for ($i = 0; $i < count($gradeList1['grade']); $i++) {
$first = $gradeList1['grade'][$i];
$second = $gradeList2['grade'][$i];
$result['show_result'][] = (int)$first + (int)$second;
}
var_dump($result);
for example i have the following codes in my controller:
foreach($-request->input('text') as $var){
$sum[] = $var;
}
$last = sizeof($request->input('text'));
$i = 0;
while($i < $last)
{
//insert code here
$i++;
}
$request->input('text') has the following values:
['1,2,3,4,5']
how do you add the values in the variable $var[] in eloquent? i tried the sum but it didn't work. someone also said ill use += sign on my increment
explode to convert comma-separated numbers into an array.
intval on all array elements using array_map to cast them into integer.
array_sum to add them all.
Try this.
$array = $request->input('text'); // ['1, 2, 3, 4, 5'];
$string_numbers = explode(', ', $array[0]); // ['1', '2', '3', '4', '5']
$numbers = array_map('intval', $string_numbers); // [1, 2, 3, 4, 5]
echo array_sum($numbers); // 15
$num = ['1,2,3,4,5']; // when $n = $request->input('text');
$numbers = explode(',', $num[0]);
$sum = array_sum($numbers);
dd($sum);
I think this will be helpful to you
I'v written 2 codes to shuffle some arrays whitch are in a for loop
First:
$numbers = range(0, sizeof($array_id)-1);
shuffle($numbers);
foreach ($numbers as $number) {
$arr = array("user" => array("id" => $array_id[$number], "name" => $array_name[$number], "key" => $array_key[$number]));
}
echo json_encode($arr);
This one has a big problem and that's if the $number in one of the arrays equals to 5 it won't loop to put another result of $number in the that array, for example the result would be something like this:
{"user":{"id":["18","2","36"],"name":["alex","john"],"key":["159","228,"486,"852"]]}}
All of my arrays have 5 values in them and you can see it returned them defectively.I'll be thankful if anyone can tell me why when $number gets the max value in range by shuffle and array gets that $number it stocks?
Second:
function shuffle_assoc(&$array) {
if (shuffle($array)) {
return $array;
}else{
return FALSE;
}
}
for ($y=0; $y<sizeof($array_id); $y++) {
$arr = array("user" => array("id" => shuffle_assoc($array_id), "name" => shuffle_assoc($array_name), "key" => shuffle_assoc($array_key)));
}
echo json_encode($arr);
This one works fine But I want the id and name to be match I mean they shuffle the same(if $array_id[2] then array_name[2]) that's why I wrote the first code.anyway for this one if anyone knows how to make id and name shuffle the same I'll be appreciate that.(sorry if I had mistakes in my writing my first language isn't English but I love English :)
I'm not sure that I completely understood you, but
$numbers = range(0, 5);
// $number = array(0, 1, 2, 3, 4, 5)
All of my arrays have 5 values
It's
$array_id[0]
$array_id[1]
$array_id[2]
$array_id[3]
$array_id[4]
So you haven't $array_id[5]. I think you need $numbers = range(0, 4);
EDIT:
Once again, I'm not sure if you want this to happen.
<?php
$array_id = array(1,2,3,4,5);
$array_name = array('a','b','c','d','e');
$numbers = range(0, 4);
shuffle($numbers);
$arr = array();
foreach ($numbers as $number) {
$arr["id"][] = $array_id[$number];
$arr["name"][] = $array_name[$number];
}
$arr2 = array("user" => array("id" => $arr["id"], "name" => $arr["name"]));
echo json_encode($arr2);
?>
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 2 years ago.
For example if a matrix is:
1 2
3 4
5 6
Then transpose of above matrix will be:
1 3 5
2 4 6
This is my current code:
<?php
// transpose matrix
$trans = array(
array(1, 2),
array(3, 4),
array(5, 6)
);
foreach ($trans as $key => $val){
foreach ($trans[$key] as $k => $v){
echo $v;
}
}
?>
There's a quirky PHP way to transpose a 2d array:
$trans = array(
array(1, 2),
array(3, 4),
array(5, 6)
);
array_unshift($trans, null);
$trans = call_user_func_array('array_map', $trans);
var_dump($trans);
Demo
EDIT Easier approach using PHP 5.6 array unpacking
With the introduction of the array argument unpacking feature in PHP 5.6, we can simplify this still further:
$trans = array(
array(1, 2),
array(3, 4),
array(5, 6)
);
$trans = array_map(null, ...$trans);
var_dump($trans);
EDIT Explanation
Quoting from the PHP docs for the array_map() function:
An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function
(See Example #4 from that docs page for an example of what this does)
The array_unshift($trans, null) that we perform first is providing that NULL callback, and we use call_user_func_array() because we don't necessarily know how many values there are in our $trans array. What we're doing using that call_user_func_array() is the equivalent of:
$trans = array_map(NULL, $trans[0], $trans[1], $trans[2]);
for your example array, because the top-level of your 2-d array has three elements (keys 0, 1 and 2).
Effectively, this NULL callback loops through all the arrays in parallel taking each value from them in turn to build a new array:
$maxArraySize = max(count($array[0], $array[1], $array[2]);
// $maxArraySize will have a value of 2 in your case,
// because your sub-arrays are all equal size
$newArray = [];
for($i = 0; $i < $maxArraySize; ++$i) {
$tmpArray = [];
$tmpArray[] = $array[0][$i];
$tmpArray[] = $array[1][$i];
$tmpArray[] = $array[2][$i];
$newArray[] = $tmpArray[];
}
There's a couple of extra checks in there
it doesn't care if your arrays are associative or enumerated in either dimension, because it accesses the $ith element, not the index
If the sub-arrays aren't all the same length, then it effectively pads the shorter sub-arrays with null values to match the length of the longest
It doesn't matter how many arrays you pass in, it will work with them all in parallel
I believe this works with rectangular arrays as well.
The trick: return array_map(null, ...$squareArray); seems to work in an unexpected way for a single column array
function RotateSquare2DArray($squareArray)
{
if ($squareArray == null) { return null; }
$rotatedArray = array();
$r = 0;
foreach($squareArray as $row) {
$c = 0;
if (is_array($row)) {
foreach($row as $cell) {
$rotatedArray[$c][$r] = $cell;
++$c;
}
}
else $rotatedArray[$c][$r] = $row;
++$r;
}
return $rotatedArray;
}
If the array is associative, I use this
function RotateSquareAssociativeArray($squareArray)
{
if ($squareArray == null) { return null; }
$rotatedArray = array();
$r = 0;
foreach($squareArray as $c=>$row) {
if (is_array($row)) {
foreach($row as $key=>$cell) {
$rotatedArray[$key][$c] = $cell;
}
}
else {
$rotatedArray[$c][$r] = $row;
}
++$r;
}
return $rotatedArray;
}
i have 2 arrays of PHP, one having ids of online users and second having ids of idle users, but in idle users array some ids of online user's also exist, i want to compare both arrays and remove user ids from 2nd array in php. how can i do this?
use
$idleWithoutOnline = array_diff($idleUsers, $onlineUsers);
http://php.net/manual/en/function.array-diff.php
yes thats possible by array_diff
have a look at
http://php.net/manual/en/function.array-diff.php
Use this
$array1 = array('[param1]' ,'demo' ,'[param2]' ,'some' ,'[param3]');
$array2 = array('value1' ,'demo' ,'value2' ,'some' ,'value3');
array_unique( array_merge($arr_1, $arr_2) );
or you can do:
$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);
$online_users = array(1, 5, 7, 8);
$idle_users = array(6, 4, 5, 8, 9);
for($i = 0; $i < count($idle_users); $i++)
{
foreach($online_users as $v)
{
if($idle_users[$i] == $v)
{
unset($idle_users[$i]);
}
}
}
print_r($idle_users); // This will give you 6,4,9 as idle users