PHP get ranges of same values from array - php

Is there any way to get the key range of same values and make a new array?
Let's say we have an Array Like this in php :
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b','6'=>'a','7'=>'a'];
How can i get this array? Is there any function for this?
$second_array = ['1-3'=>'a','4-5'=>'b','6-7'=>'a'];

Loop through it, extract the keys, generate the ranges and insert to the new array -
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b'];
$flip = array();
foreach($first_array as $key => $val) {
$flip[$val][] = $key;
}
$second_array = [];
foreach($flip as $key => $value) {
$newKey = array_shift($value).' - '.end($value);
$second_array[$newKey] = $key;
}
Output
array(2) {
["1 - 3"]=>
string(1) "a"
["4 - 5"]=>
string(1) "b"
}

regarding your first question you can get range of each value using foreach() loop.
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b'];
foreach($first_array as $key=>$value)
{
//do your coding here, $key is the index of the array and $value is the value at that range, you can use that index and value to perform array manipulations
}
Regarding your second question it not exactly clear what are trying to implement there. But what ever you want to do like creating a new array with modified index and other things can be done within this foreach() loop itself
I hope this helps you.

If someone is still looking for an answer, here is what I did.
Given the array
$first_array = ['0'=>'a',
'1'=>'a',
'2'=>'a',
'3'=>'a',
'4'=>'a',
'5'=>'b',
'6'=>'b',
'7'=>'a',
'8'=>'a']
I build a multidimensional array, in which each element is an array of three more elements:
[0] - The value in the first array
[1] - The key where the value starts repeating
[2] - The last key where the value stops repeating
The code
$arrayRange = [];
for($i = 0; $i < count($first_array); $i++){
if(count($arrayRange) == 0){
// The multidimensional array is still empty
$arrayRange[0] = array($first_array[$i], $i, $i);
}else{
if($first_array[$i] == $arrayRange[count($arrayRange)-1][0]){
// It's still the same value, I update the value of the last key
$arrayRange[count($arrayRange)-1][2] = $i;
}else{
// It's a new value, I insert a new array
$arrayRange[count($arrayRange)] = array($first_array[$i], $i, $i);
}
}
}
This way you get a multidimensional array like this:
$arrayRange[0] = array['a', 0, 4];
$arrayRange[1] = array['b', 5, 6];
$arrayRange[2] = array['a', 7, 8];

Related

Set variable from an array in Laravel

The dump of the following array is:
$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
array(2) { [60]=> int(116) [50]=> int(117) }
As shown above, the key is 60 and 50 (which is qcounter), while the value is 116 and 117 (which is id).
I'm trying to assign the qcounter to a variable as follows, but with a fixed index, such as 0,1,2,3 .. etc :
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
And the same with id :
$id1= $quest_all[0];
$id2= $quest_all[1];
Any help is appreciated.
Try as below:
One way is:
array_values($quest_all); will give you an array of all Ids
array_keys($quest_all); will give an array of all qcounters and respective indexes for qcounter and ids will be the same.
Other way, First get all qcounters only from collection:
$quest_all = $qwinners->pluck('qcounter')->toArray();
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
...
and so on
Then get all ids
$quest_all = $qwinners->pluck('id')->toArray();
$id1= $quest_all[0];
$id2= $quest_all[1];
...
and so on
You can also use foreach to iterate through the result array.
To reset array keys, use array_values().
To get array keys, use array_keys():
$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
$quest_all_keys = array_keys($quest_all);
$quest_all_values = array_values($quest_all);
Or simply use foreach():
$keys = [];
$values = [];
foreach($quest_all as $key => $value){
$keys[] = $key;
$values[] = $value;
}
I am not sure why you want variable names incrementing when you could have an array instead but if you don't mind an underscore, '_' in the name and them starting at 0 index you can use extract to create these variables. (As an exercise)
$quest_all = ...;
$count = extract(array_keys($quest_all), EXTRA_PREFIX_ALL, 'qcounter');
extract(array_values($quest_all), EXTRA_PREFIX_ALL, 'id');
// $qcounter_0 $qcounter_1
// $id_0 $id_1
for ($i = 0; $i < $count; $i++) {
echo ${'qcounter_'. $i} .' is '. ${'id_'. $i} ."\n";
}
It would probably be easier to just have the 2 arrays:
$keys = array_keys($quest_all);
$values = array_values($quest_all);

PHP create 1 array of 4 arrays ordered by index

I have 4 arrays, each one holds another column of a table, I would like to create one array with the data ordered per array[$i]. All arrays have the same number of values: $namesArr, $folderArr, $updatedAt, $valuesArr .
I would like my new array to be contain:
$namesArr[0], $folderArr[0], $updatedAt[0], $valuesArr[0],
$namesArr[1], $folderArr[1], $updatedAt[1], $valuesArr[1],
$namesArr[2], $folderArr[2], $updatedAt[2], $valuesArr[2],
...
I guess the solution is pretty simple, but I got stuck :(
Can anyone help?
I would do something like:
$arr = array_map(function () { return func_get_args(); },$namesArr, $folderArr, $updatedAt, $valuesArr);
You can use foreach loop to merge 4 arrays:
foreach ($namesArr as $key => $value) {
$arr[$key][] = $value;
$arr[$key][] = $folderArr[$key];
$arr[$key][] = $updatedAt[$key];
$arr[$key][] = $valuesArr[$key];
}
Thus $arr will be the merged array
<?php
$newArr = array();
for ($i = 0; $i < count($namesArr); $i++)
{
$newArr[$i][0] = $namesArr[$i];
$newArr[$i][1] = $folderArr[$i];
$newArr[$i][2] = $updatedAt[$i];
$newArr[$i][3] = $valuesArr[$i];
}
?>
Explanation
What this will do is iterate depending on how many elements there are in $namesArr.
I utilised a multidimensional array here so that the first set of square brackets is effectively the "row" in a table, and the second set of square brackets are the "column" of a table.
do the following way:
while($db->query($sql)){
$namesArr[] =$db->f('names');
$folderArr[]=$db->f('folder');
$updatedAt[]=$db->f('updated');
$valuesArr[]=$db->f('values');
}

PHP Extract and count first elements of each element in multidimensional array

I have this array in php,
$mainArray = array(
array("apple","two", "grren"),
array("samsung","five", "red"),
array("microsoft","one","gray"),
array("apple","nine", "blue"),
array("samsung","ten", "white"),
array("nokia","seven", "yellow")
);
I can easily loop through it and extract all the first entries of each array like this:
foreach($mainArray as $w => $n) {
$whatever = $mainArray[$w][0];
}
I'm trying to count how many entries are the same in the first element of each array, and have a result of something like:
apple (2)
samsung (2)
microsoft (1)
nokia (1)
I'm just not sure what is the correct way to do this.
Thank you in advance.
print_r(
array_count_values(
array_map('array_shift', $mainArray)
)
);
Output (Demo):
Array
(
[apple] => 2
[samsung] => 2
[microsoft] => 1
[nokia] => 1
)
So even I am a big fan of foreach, why did I not use it here?
First of all, to count values in an array, in PHP we have array_count_values. It does the job for us.
So the only problem left was to get all the first items into an array to count them with array_count_values. That is a typical mapping job, and I like mapping, too, next to foreach so I tried if array_map together with array_shift worked - and it did.
However you might want to look for a function called array_column. It's not yet available with PHP itself, but as PHP code in another answer:
$counts = array_count_values(array_column($mainArray, 0));
$count = array();
foreach($mainArray as $array) {
$first = $array[0];
if(!isset($count[$first])) $count[$first] = 0;
$count[$first]++;
}
print_r($count);
Collect every first element of the deep arrays by pushing them into a new array ($result in my example) and then call array_count_values() on that array. Like so:
$mainArray = array(
array("apple","two", "grren"),
array("samsung","five", "red"),
array("microsoft","one","gray"),
array("apple","nine", "blue"),
array("samsung","ten", "white"),
array("nokia","seven", "yellow")
);
$result = array();
foreach( $mainArray as $k => $v )
{
// let's continue if $v is not an array or is empty
if( !is_array( $v ) || empty( $v ) ) continue;
$result[] = $v[ 0 ];
}
var_dump( array_count_values( $result ) );
You can loop through the $mainArray to build a full array/list of values and then use array_count_values() on that:
$firstElements = array();
foreach ($mainArray as $arr) {
$firstElements[] = $arr[0];
}
$counts = array_count_values($firstElements);
Another option would be to loop through $mainArray and insert the value as an index for an array (if it doesn't already exist) and then increment it each time (this will do the same thing as array_count_values() in the end):
$counts = array();
foreach ($mainArray as $arr) {
if (!isset($counts[$arr[0]])) $counts[$arr[0]] = 0;
$counts[$arr[0]]++;
}
You can do it just like this:
foreach($mainArray as $n) {
$count[$n[0]] = isset($count[$n[0]]) ? $count[$n[0]]++ : 1;
}
var_dump($count); //should give you something like
/*
array(4) {
["apple"]=>
int(2)
["samsung"]=>
int(2)
["microsoft"]=>
int(1)
["nokia"]=>
int(1)
}
*/

PHP : How to get sum of multidimensionnal arrays with specific keys?

I would like to know how to get the sum of some key values of multi-dimensional arrays, knowing that some keys are variables; here is an example of the situation :
The array could be written like this :
$array[$dim1][$dim2][$dim3][$dim4] = $variable_value;
$dim1, 2, 3 and 4 are arrays with dimensions, and we don't know the name of the $dim1, 2, 3 and 4.
We want the sum of all $variable_value of each dimensions, but we can't do array_sum($array[$dim1][$dim2][$dim3][$dim4]) because the $dim are not known.
The algorithm I need to find must permit me to apply filters on the sums, like "get the sum of all the $variable_value where $dim3 = $variableX...", so a function like this :
function array_sum_filter($array, $dimension, [$filter_on_key_value])
Any ideas?
use for/foreach loops for looping through the multidimensional array and an if statement to check if $dim3 = $variableX...
You can try this using RecursiveArrayIterator and RecursiveIteratorIterator
$sum = 0;
$specific = 0;
$array = array();
$array["A"]["B"]["C"]["D"] = 5;
$array["A"]["B"]["K"]["D"] = 3;
$array["A"]["C"] = 2;
$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ( $array_obj as $key => $value ) {
$sum += $value;
if ($key == "D")
$specific += $value;
}
echo $sum, PHP_EOL;
echo $specific, PHP_EOL;
Output
10
8

Comparing arrays and giving out numbers depending on what value is in what array

This is more a kind of logical Question. Sometimes i think my Brain is not for programming ;(
What i want to do is.
IF array1 and array2 have the same values setup a new array with keyname to the value that the both array have in common and value = 3 OK i already got that.
Now i want:
IF a value is ONLY in array1 set new array value = 1
IF a value is ONLY in array2 set new array value = 2
$beidesgeht = array_intersect($acc_conf, $ano_conf);
foreach ( $beidesgeht as $be ) {
$fertig[ $be ] = 3;
}
I guess thats a easy one for you pros. ;)
After what you've got up there:
foreach ($acc_conf as $el) {
if (!isSet($fertig[$el])) {
$fertig[$el] = 1;
}
}
foreach ($ano_conf as $el) {
if (!isSet($fertig[$el])) {
$fertig[$el] = 2;
}
}

Categories