This question already has answers here:
Combine two arrays
(11 answers)
Closed 6 months ago.
i have two arrays in php
Array
(
[0]=>30
)
Array
(
[0]->43
)
i want to merge these arrays in a single array my desired output is
Array
(
[0]=>30
[1]=>43
)
can anyone tell me how to achieve this
function get_minutes($sess_time)
{
# code...
if (strstr($sess_time, ':'))
{
$separatedData = split(':', $sess_time);
$minutesInHours = $separatedData[0] * 60;
$minutesInDecimals = $separatedData[1];
$totalMinutes = $minutesInHours + $minutesInDecimals;
}
else
{
$totalMinutes = $sess_time * 60;
}
if ($totalMinutes<=60)
{
# code...
return $totalMinutes;
}
else
{
$result=$totalMinutes/60;
$y=explode(".",$result);
$hours=$y[0];
$hours_mins=$hours*60;
$remaining_mins=$totalMinutes-$hours_mins;
$remaining_array=array($remaining_mins);
print_r($remaining_array);
}
}
when i print the remaining array the ourput is two arrays
Try to use array_merge function.
array_merge — Merge one or more arrays
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
Output:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
Reference: http://www.w3schools.com/php/func_array_merge.asp
Related
This question already has answers here:
Move array item with certain key to the first position in an array, PHP
(9 answers)
move array element to the first position but remain order
(4 answers)
Move an array element to a new index in PHP
(9 answers)
Move Value in PHP Array to the Beginning of the Array
(12 answers)
Move array element with a particular value to top of array
(2 answers)
Closed 2 months ago.
How to sort an array at PHP to force selected row as a first ?
My array is
array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');
How to sort the array to force
array[]=array(id=>'b', content=>'apple');
as a first row and doesn't matter the rest (apple is the key).
And in other example turn sort to get
array[]=array(id=>'d', content=>'cherry');
as a first row and doesn't matter the rest (cherry is the key).
Another way to do this is to effectively rotate the array using array_slice, bringing the element you want to the start:
$first = 'apple';
$k = array_search($first, array_column($array, 'content'));
$array = array_merge(array_slice($array, $k), array_slice($array, 0, $k));
print_r($array);
Output:
Array (
[0] => Array ( [id] => b [content] => apple )
[1] => Array ( [id] => c [content] => banana )
[2] => Array ( [id] => d [content] => cherry )
[3] => Array ( [id] => a [content] => lemon )
)
Demo on 3v4l.org
There are 2 ways I can think of doing this. The first is as Ultimater in the comments suggest to extract the matching row, then sort and then add the row back in...
$first = 'apple';
$array = [];
$array[]=array('id'=>'a', 'content'=>'lemon');
$array[]=array('id'=>'b', 'content'=>'apple');
$array[]=array('id'=>'c', 'content'=>'banana');
$array[]=array('id'=>'d', 'content'=>'chery');
$firstElement = array_search($first, array_column($array, "content"));
$row = $array[$firstElement];
unset($array[$firstElement]);
sort($array);
array_unshift($array, $row);
print_r($array);
The second is to use usort and add specific clauses in that if the key matches the row you want first, then it will always force it to the first row...
$first = 'apple';
usort($array, function ($a, $b) use ($first){
if ( $a['content'] == $first) {
return -1;
}
if ( $b['content'] == $first) {
return 1;
}
return $a <=> $b;
});
print_r($array);
(I've used <=> in this which is PHP 7+, there are alternatives if you need to use PHP 5).
If as your comment suggests that there is no need to sort the rest of the data, then the first set of code minus the sort() should do.
One other option - if id:content is one to one, we can index the array by content and merge with an array with a single empty "apple" key (or whichever content value you're looking for).
$array = array_merge(['apple' => []], array_column($array, null, 'content'));
If the resulting string keys are undesirable the array can be reindexed with array_values.
If the array only contains id and content and id:content is in fact one to one, a "dictionary" of key-value pairs will be handier to deal with than a list of rows like this and it would probably be better to set the array up that way to begin with if possible.
If id:content is not one to one, then... never mind. ;-)
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
any particular function or code to put this kind of array data
ori [0] => 43.45,33,0,35 [1] => 74,10,0,22 [2] => 0,15,0,45 [3] => 0,0,0,340 [4] => 12,5,0,0 [5] => 0,0,0,0
to
new [0] => 43.45,74,0,0,12,0 [1] => 33,10,15,0,5,0 [2] => 0,0,0,0,0,0, [3] => 35,22,45,340,0,0
As you can see, the first value from each ori are inserted into the new(0), the second value from ori are inserted into new(1) and so on
If $ori is an array of arrays, this should work:
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$newArray = transpose($ori);
Note: from Transposing multidimensional arrays in PHP
If $ori is not an array of arrays, then you'll need to convert it first (or use the example by Peter Ajtai), like this:
// Note: PHP 5.3+ only
$ori = array_map(function($el) { return explode(",", $el); }, $ori);
If you are using an older version of PHP, you should probably just use the other method!
You essentially want to transpose - basically "turn" - an array. Your array elements are strings and not sub arrays, but those strings can be turned into sub arrays with explode() before transposing. Then after transposing, we can turn the sub arrays back into strings with implode() to preserve the formatting you want.
Basically we want to go through each of your five strings of comma separated numbers one by one. We take each string of numbers and turn it into an array. To transpose we have to take each of the numbers from a string one by one and add the number to a new array. So the heart of the code is the inner foreach(). Note how each number goes into a new sub array, since $i is increased by one between each number: $new[$i++][] =$op;
foreach($ori as $one) {
$parts=explode(',',$one);
$i = 0;
foreach($parts as $op) {
$new[$i++][] =$op;
}
}
$i = 0;
foreach($new as $one) {
$new[$i++] = implode(',',$one);
}
// print_r for $new is:
Array
(
[0] => 43.45,74,0,0,12,0
[1] => 33,10,15,0,5,0
[2] => 0,0,0,0,0,0
[3] => 35,22,45,340,0,0
)
Working example
I have two assoc array i want to creat one array out of that
E.g
a(a=>1
b=>3
f=>5
)
b(a=>4
e=>7
f=>9
)
output must be
c(
a=>1
b=>3
f=>5
a=>4
e=>7
f=>9
)
i am new in php
Use array_merge(). Your resulting array CAN NOT have more than one entry for the same key, so the second a => something will overwrite the first.
Use the + operator to return the union of two arrays.
The new array is constructed from the left argument first, so $a + $b takes the elements of $a and then merges the elements of $b with them without overwriting duplicated keys. If the keys are numeric, then the second array is just appended.
This ey difference of the + operator and the function, array_merge is that array merge overwrites duplicated keys if the latter arguments contain that key. The documentation puts it better:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If the keys are different, then use array_merge()
<?php
$a1=array("a"=>"Horse","b"=>"Cat");
$a2=array("c"=>"Cow");
print_r(array_merge($a1,$a2));
?>
OUTPUT:
Array ( [a] => Horse [b] => Cat [c] => Cow )
If the keys are the same, then use array_merge_recursive()
<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>
OUTPUT:
Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue
)
[0] => 5
[1] => 10
)
This question already has answers here:
How to re-index the values of an array in PHP? [duplicate]
(3 answers)
How to sort an array by keys in an ascending direction?
(3 answers)
Closed 2 years ago.
I have an array with numerical indices, which looks like this (after I unset some elements):
$array = [
23 => 'banana',
3 => 'apple',
5 => 'pear',
];
Which function do I use to reorder them based on their key order to:
$array = [
0 => 'apple',
1 => 'pear',
2 => 'banana',
];
I tried some of the sort functions but none of them provided the output I need.
If you want to sort the array by key value use ksort():
ksort($array);
print_r($array);
Output:
Array
(
[3] => apple
[5] => pear
[23] => banana
)
That will preserve the keys however. To reassign keys for an array from 0 onwards use array_values() on the result:
ksort($array);
$array_with_new_keys = array_values($array); // sorted by original key order
print_r($array_with_new_keys);
Output:
Array
(
[0] => apple
[1] => pear
[2] => banana
)
ksort() will sort by key, then get the values with array_values() and that will create a new array with keys from 0 to n-1.
ksort($array)
$array = array_values( $array );
Of course, you don't need ksort if it's already sorted by key. You might as well use array_values() directly.
$arrayOne = array('one','two','three'); //You set an array with certain elements
unset($array[1]); //You unset one or more elements.
$arrayTwo = array_values($arrayOnw); //You reindex the array into a new one.
print_r($arrayTwo); //Print for prove.
The print_r results are:
Array ( [0] => one [1] => three )
I have two arrays of values that I would like to combine - but the only methods that PHP provides seem to combine by key instead of value. Here is a hack that I was able to use to get this to work, but I am wondering if there is a better method or a native function that I have missed. It's been a while since I last used arrays and it seems like there is an easy answer to this.
//Input arrays that we want to combine into one array
$array = array(2, 3, 4, 5);
$array2 = array(5, 6, 1);
//Flip values and keys
$array = array_flip($array);
$array2 = array_flip($array2);
//Combine array
$array3 = $array2 + $array;
//flip array keys back to values
$array3 = array_keys($array3);
//Optional sort
sort($array3);
print_r($array3);
Which returns the combined values of the two arrays:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Not entirely sure what you are trying to accomplish. I am assuming you are trying to combine 2 arrays without having any duplicates. If this is the case then the following would work
$newarr = array_unique(array_merge($array, $array2));