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);
Related
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
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);
I can't seem to find the answer to these problem. I have the following php code.
$r = 1,2,3,4,5,6 and so on
and i want to get the number like this
$result = 1,3,5
or if i have
$s = b,c,d,e,f,g,h,i...and so on
the result should be
$results c,e,g,i
Pretty easy with numbers, the trick with letters is to use ord()
$arr = array(1,2,3,4,5,6);
$arr = array_filter ($arr, function ($number) {
return $number % 2;
});
print_r($arr);
$arr = array('a', 'b', 'c', 'd', 'e');
$arr = array_filter ($arr, function ($letter) {
return ord($letter) % 2;
});
print_r($arr);
Output :
Array (
[0] => 1
[2] => 3
[4] => 5
)
Array (
[0] => a
[2] => c
[4] => e
)
And here is a generic solution, working with both letters and numbers :
$arr = array_filter ($arr, function ($value) {
$value = is_int($value) ? $value : ord($value);
return $value % 2;
});
This will work:
$a = array(1,2,3,4,5,6);
foreach($a as $k => $v){
if($k&1){
unset($a[$k]);
}
}
print_r($a);
What would be the most efficient way of counting the number of times a value appears inside an array?
Example Array ('apple','apple','banana','banana','kiwi')
Ultimately I want a function to spit out the percentages for charting purposes
(e.g. apple = 40%, banana = 40%, kiwi = 20%)
Just put it through array_count_values. The percentages should be easy...
$countedArray = array_count_values($array);
$total = count($countedArray);
foreach ($countedArray as &$number) {
$number = ($number * 100 / $total) . '%';
}
Use array_count_values():
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
$a = Array ('apple','apple','banana','banana','kiwi');
$b = array_count_values($a);
function get_percentage($b,$a){
$a_count = count($a);
foreach ($b as $k => $v){
$ret[$k] = $v/$a_count*100."%";
}
return $ret;
}
$c = get_percentage($b,$a);
print_r($c);