Here is my code:
$arr = array();
$arr[] = 1;
$arr['txt'] = 'something';
$arr['txt2'] = 'something2';
$arr[] = 2;
$arr[] = 3;
echo '<pre>';
print_r($arr);
/* output:
1
something
something2
2
3
*/
I'm trying to change array's order and make this result:
/* expected output:
1
2
3
something
something2
*/
As you see, I need to reindex all array's items and put the numeric ones in the beginning of array. Is that possible?
How can I separate numeric array's keys from the letter keys?
Simplest way is to sort the array by key, using ksort which modifies the array in place. Use the SORT_STRING flag to get the result you seek:
ksort($myArr, SORT_STRING);
Live demo
The Correct syntax is:
- Using array values
<?php
$arr = array();
$arr[] = 1;
$arr['txt'] = 'something';
$arr['txt2'] = 'something2';
$arr[] = 2;
$arr[] = 3;
echo '<pre>';
usort($arr, function($a, $b) {
if (is_float($a)) {
if ( is_float($b)) {
return $a - $b;
}
else
return -1;
}
elseif (is_float($b)) {
return 1;
}
else {
return strcmp($a, $b);
}
});
print_r($arr);
?>
OUTPUT
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => something
[4] => something2
)
- Using array index values
<?php
$arr = array();
$arr[] = 1;
$arr['txt'] = 'something';
$arr['txt2'] = 'something2';
$arr[] = 2;
$arr[] = 3;
echo '<pre>';
usort($arr, SORT_STRING);
print_r($arr);
?>
OUTPUT
Array
(
[0] => 1
[1] => 2
[2] => 3
[txt] => something
[txt2] => something2
)
phphtml
Related
I am trying to get an factorial value of each item in array by using this method but this outputs only one value
can any body help me finding where i am doing wrong?
function mathh($arr, $fn){
for($i = 1; $i < sizeof($arr); $i++){
$arr2 = [];
$arr2[$i] = $fn($arr[$i]);
}
return $arr2;
}
$userDefined = function($value){
$x = 1;
return $x = $value * $x;
};
$arr = [1,2,3,4,5];
$newArray = mathh($arr, $userDefined);
print_r($newArray);
You're going to need a little recursion so in order to do that you need to pass the lambda function into itself by reference:
function mathh($arr, $fn){
$arr2 = []; // moved the array formation out of the for loop so it doesn't get overwritten
for($i = 0; $i < sizeof($arr); $i++){ // starting $i at 0
$arr2[$i] = $fn($arr[$i]);
}
return $arr2;
}
$userDefined = function($value) use (&$userDefined){ // note the reference to the lambda function $userDefined
if(1 == $value) {
return 1;
} else {
return $value * $userDefined($value - 1); // here is the recursion which performs the factorial math
}
};
$arr = [1,2,3,4,5];
$newArray = mathh($arr, $userDefined);
print_r($newArray);
The output:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
)
I wanted to expand on this some since you're essentially (in this case) creating an array map. This could be handy if you're doing additional calculations in your function mathh() but if all you want to do is use the lambda function to create a new array with a range you could do this (utilizing the same lambda we've already created):
$mapped_to_lambda = array_map($userDefined, range(1, 5));
print_r($mapped_to_lambda);
You will get the same output, because the range (1,5) of the mapped array is the same as your original array:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
)
I have a dynamic variable a with different values
$a = (1,2,3,4,5);
$a = (2,3,4,5,6);
I want a result that will sum each index of each array
$a = (3,5,7,9,11);
while($row=mysqli_fetch_array($sql)){
$a = explode(',',$row['array']); //array with same variable name
}
You could use array_map:
$a = array();
while($row=mysqli_fetch_array($sql)){
$a = array_map(function ($x, $y) { return $x + $y; }, $a, explode(',',$row['array']));
}
print_r($a);
Assuming your code returns rows of
$row['array'] = '1,2,3,4,5';
$row['array'] = '2,3,4,5,6';
The output will be:
Array
(
[0] => 3
[1] => 5
[2] => 7
[3] => 9
[4] => 11
)
May be below code will help you out
$a = array(1,2,3,4,5,4,5);
$b = array(2,3,4,5,6,7,3);
foreach($a as $k=>$v)
{
$temp = $a[$k]+$b[$k];
$c[] = $temp;
}
print_r($c);
I have an array containing multiple arrays like
$A = array();
$A[0] = array("1","2","3","4","5");
$A[1] = array("1","6","7","8");
$A[2] = array("0","1","3");
I want to sort the values in multiple arrays in the order of frequency and put them into another array let's say $B.
The values in $B is "1","1","1","3","3","0","2","4","5","6","7","8".
$A = array();
$A[0] = array("1","2","3","4","5");
$A[1] = array("1","6","7","8");
$A[2] = array("0","1","3");
//Merging above array in to one array
$merged = array_values(call_user_func_array('array_merge', $A));
//Getting occurrence count
$counts = array_count_values($merged);
//Sort by count
arsort($counts);
//Adding to required array
$B = array();
foreach ($counts as $k => $v)
for($i=1;$i<=$v;$i++)
$B[] = $k;
echo "<pre>";
print_r($B);
echo "</pre>";
Result
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 3
[4] => 3
[5] => 0
[6] => 8
[7] => 7
[8] => 5
[9] => 2
[10] => 4
[11] => 6
)
First merge all arrays
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$resultado = array_merge($array1, $array2);
see -> http://php.net/manual/es/function.array-merge.php
Second sort the big array
arsort($resultado );
see -> http://php.net/manual/es/array.sorting.php
Use a hash table to count the frequency of each number, and then store them in the decreasing order of frequency in array $B, like this:
$hash_table = array();
foreach($A as $array){
foreach($array as $value){
if(empty($hash_table[$value])){
$hash_table[$value] = 1;
}else{
$hash_table[$value] += 1;
}
}
}
arsort($hash_table);
$B = array();
foreach($hash_table as $key => $value){
for($i = 0; $i < $value; ++$i){
$B[] = $key;
}
}
var_dump($B); // to see the contents of array $B
If order of same occurance count items isn't important, you can use:
// Merge all arrays
$counts = array_count_values(call_user_func_array('array_merge', $A));
// Sort by occurance
arsort($counts);
// Add [value] to new array [occurance] times
$B = array();
array_walk($counts, function($occurances, $value) use (&$B){
for($i=0;$i<$occurances;$i++) $B[] = $value;
});
echo implode(',', $B);
Output
1,1,1,3,3,0,8,7,5,2,4,6
Array print in order of count and index:
$temp = array();
foreach($A as $b){
foreach($b as $c){
if(isset($tmep[$c])){
$tmep[$c]++;
}else{
$tmep[$c] = 1;
}
}
}
function SortArrayByKeyThanValue (&$pArray, $pSortMethodForKey = SORT_ASC, $pSortMethodForValue = SORT_DESC){
# check user input: sorting is not necessary
if (count($pArray) < 2)
return;
# define $k and $v as array_multisort() needs real variables, as user input is put by reference
$k = array_keys ($pArray);
$v = array_values($pArray);
array_multisort(
$v, $pSortMethodForValue,
$k, $pSortMethodForKey
);
$pArray = array_combine($k, $v);
}
SortArrayByKeyThanValue($tmep);
$B = array();
array_walk($tmep, function($occurances, $value) use (&$B){
for($i=0;$i<$occurances;$i++) $B[] = $value;
});
echo implode(',', $B);
Here is my array:
$var = array('a', 'b');
Now I want to define a range for each key. For example:
5 keys set on each value of array:
echo $var[0]; // output: a
echo $var[1]; // output: a
echo $var[2]; // output: a
echo $var[3]; // output: a
echo $var[4]; // output: a
echo $var[5]; // output: b
echo $var[6]; // output: b
echo $var[7]; // output: b
echo $var[8]; // output: b
echo $var[9]; // output: b
In fact I want something like this:
$var = array( '0'=>'a', '1'=>'a', '2'=>'a', '3'=>'a', '4'=>'a',
'5'=>'b', '6'=>'b', '7'=>'b', '8'=>'b', '9'=>'b' );
But in reality I can not define a rage of keys for each value, because the values are too much. It should be noted that I can implement it via if-else statement (without array), But in this case, performance will drop dramatically. something like this:
if (0 <= $i <=4) { $var = 'a'; }
elseif (5 <= $i <=9) { $var = 'b'; }
But as I said, the values are too much and I can not define a range for each value manually. So there is any solution ? (set 5 keys for each value dynamically)
$arr = array('a', 'b');
$i = 6; // for e.g.
$var = $arr[floor($i/5)];
// output: b
This should work for you:
Just loop through your array and array_fill() your result array with each value as many times as you want, e.g.
<?php
$var = array('a', 'b');
$amount = 5;
$result = [];
foreach($var as $k => $v)
$result = $result + array_fill($k*$amount, $amount, $v);
print_r($result);
?>
output:
Array
(
[0] => a
[1] => a
[2] => a
[3] => a
[4] => a
[5] => b
[6] => b
[7] => b
[8] => b
[9] => b
)
$var = array( '0'=>'a', '1'=>'b');
$new_array = array();
foreach ($var as $key => $value) {
for($i = 0 ; $i < 5 ; $i++){
$new_array[] = $value;
}
}
echo '<pre>';
print_r($new_array);
For example I have like more than 3 different arrays, with element like below:
1st array
hello-1
hi-1
2nd array
ok-two
hi-2
22-two
hello
3rd array
hi-3rd
hello3
And so on...
I want to combine this array in the order one by one. For example the expected output for the 3 arrays above would be:
hello-1
ok-two
hi-3rd
hi-1
hi-2
hello3
22-two
hello
I tried array_merge(). But it appends the 2nd array after the complete 1st array, which is not what I'm looking for, so here I'm kinda stuck and don't know which functions I can use here. Any hints or ideas?
This should work for you:
First I get the first element of each array into a sub array, then the second value into the next sub array and so on, that you get this structure of array:
Array
(
[0] => Array
(
[0] => hello-1
[1] => ok-two
[2] => hi-3rd
)
//...
)
After this you can just loop through each array value with array_walk_recursive() and get every value into your array.
<?php
$arr1 = [
"hello-1",
"hi-1",
];
$arr2 = [
"ok-two",
"hi-2",
"22-two",
"hello",
];
$arr3 = [
"hi-3rd",
"hello3",
];
$arr = call_user_func_array("array_map", [NULL, $arr1, $arr2, $arr3]);
$result = [];
array_walk_recursive($arr, function($v)use(&$result){
if(!is_null($v))
$result[] = $v;
});
print_r($result);
?>
output:
Array
(
[0] => hello-1
[1] => ok-two
[2] => hi-3rd
[3] => hi-1
[4] => hi-2
[5] => hello3
[6] => 22-two
[7] => hello
)
I have another way to solve this issue
<?php
$arr1 = array(
"hello-1",
"hi-1");
$arr2 = array("ok-two",
"hi-2",
"22-two",
"hello");
$arr3 = array(
"hi-3rd",
"hello3");
$max = count($arr1);
$max = count($arr2) > $max ? count($arr2) : $max;
$max = count($arr3) > $max ? count($arr3) : $max;
$result = array();
for ($i = 0; $i < $max; $i++) {
if (isset($arr1[$i])) {
$result[] = $arr1[$i];
}
if (isset($arr2[$i])) {
$result[] = $arr2[$i];
}
if (isset($arr3[$i])) {
$result[] = $arr3[$i];
}
}
print_r($result);