Count how many times a value appears in this array? - php

I have this php array named $ids:
Array (
[0] => Array ( [id] => 10101101 )
[1] => Array ( [id] => 18581768 )
[2] => Array ( [id] => 55533322 )
[3] => Array ( [id] => 55533322 )
[4] => Array ( [id] => 64621412 )
)
And I need to make a new array containing each $ids id value, as the new keys, and the times each one appears, as the new values.
Something like this:
$newArr = array(
10101101 => 1,
18581768 => 1,
55533322 => 2,
64621412 => 1,
);
This is what I have:
$newArr = array();
$aux1 = "";
//$arr is the original array
for($i=0; $i<count($arr); $i++){
$val = $arr[$i]["id"];
if($val != $aux1){
$newArr[$val] = count(array_keys($arr, $val));
$aux1 = $val;
}
}
I supose array_keys doesn't work here because $arr has the id values in the second dimension.
So, how can I make this work?
Sorry for my bad english and thanks.

array_column will create an array of all the elements in a specific column of a 2-D array, and array_count_values will count the repetitions of each value in an array.
$newArr = array_count_values(array_column($ids, 'id'));

Or do it by hand like this where $arr is your source array and $sums is your result array.
$sums = array();
foreach($arr as $vv){
$v = $vv["id"];
If(!array_key_exists($v,$sums){
$sums[$v] = 0;
}
$sums[$v]++;
}

You can traverse your array, and sum the id appearance, live demo.
$counts = [];
foreach($array as $v)
{
#$counts[$v['id']] += 1;
}
print_r($counts);

Related

Convert array in string with another array

I have a two array first is:
$array1 = ['settings:rules:key','settings:scrum:way:other'];
I have explode $array1:
$temp_array = explode(":",$array1);
Now I have another array:
$array2 = [settings] => Array
( [rules] => Array
(
[0] => Array
(
[key] =>
[showValueField] => 1
)
)
something like this.
I need to access second array with key given in first array like:
$array2['settings']['rules']['key']
I have to get this keys from first array after explode
You can do it with this kind of loop:
function getVal($path, $arr) {
$current = $arr[array_shift($path)];
while (count($path)) {
$key = array_shift($path);
if (!is_array($current) || !isset($current[$key]))
return false; // protect against non-existing keys
$current = $current[$key];
}
return $current;
}
//example used:
$arr = array("settings" => array("rules" => array("key" => "AAA")));
echo getVal(explode(":",'settings:rules:key'), $arr) . PHP_EOL;

Convert index array into multidimensional associative/index array in php

My array looks like this
Array
(
[0] => A
[1] => B
[2] => C
)
Desired array
Array
(
[0] => Array
(
[0] => A
)
[1] => Array
(
[0] => B
)
[2] => Array
(
[0] => C
)
)
I have gone through these links but didn't able to figure out the solution being a newbie.
Convert associative array into indexed
convert indexed multidimensional array to associative multidimensional array
For example:
$new_array = array_map(
function ($v) { return [$v]; },
['A', 'B', 'C']
);
This is a blanket statement on how to get your desired array :
$desired_array = array(array("0"=>"A"), array("0"=>"B"), array("0"=>"C"));
However, dynamically, you could do the following :
//Assume $original_array = array("0"=>"A", "1"=>"B", "2"=>"C");
$desired_array = array(); // New Array
for($i = 0; $i < count($original_array); $i++){ // Loop over all elements in original array
array_push($desired_array, array("0"=>$original_array[$i])); // Place each valueable as an array in new desired array
}
$arrOld = ['A','B','C','D','E'];
$arrNew = [];
foreach($arrOld as $key => $value){
$arrNew[] = [$key => $value];
}

Remove duplicates from a multi-dimensional array based on 2 values

I have an array that looks like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2"),
array("Will","Smith","4")
);
In the end I want the array to look like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2")
);
The array_unique with the SORT_REGULAR flag checks for all three value. I've seen some solutions on how to remove duplicates based on one value, but I need to compare the first two values for uniqueness.
Simple solution using foreach loop and array_values function:
$arr = array(
array("John","Smith","1"), array("Bob","Barker","2"),
array("Will","Smith","2"), array("Will","Smith","4")
);
$result = [];
foreach ($arr as $v) {
$k = $v[0] . $v[1]; // considering first 2 values as a unique key
if (!isset($result[$k])) $result[$k] = $v;
}
$result = array_values($result);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => John
[1] => Smith
[2] => 1
)
[1] => Array
(
[0] => Bob
[1] => Barker
[2] => 2
)
[2] => Array
(
[0] => Will
[1] => Smith
[2] => 2
)
)
Sample code with comments:
// array to store already existing values
$existsing = array();
// new array
$filtered = array();
foreach ($array as $item) {
// Unique key
$key = $item[0] . ' ' . $item[1];
// if key doesn't exists - add it and add item to $filtered
if (!isset($existsing[$key])) {
$existsing[$key] = 1;
$filtered[] = $item;
}
}
For fun. This will keep the last occurrence and eliminate the others:
$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
Map the array and build a key from the first to entries of the sub array
Use the returned array as keys in the new array and original as the values
If you want to keep the first occurrence then just reverse the array before and after:
$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
$array), $array));

Flatten 2D Array Into Separate Indexed Arrays

I have the array:
$total =array();
Array (
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
)
)
I need to dynamically change each array into an indexed array for a Cartesian function.
Here is how I need the code to look for the function to work correctly:
$count = cartesian(
Array(1,3),
Array(6,7,8),
Array(9,10)
);
Any help would be greatly appreciated! I have tried flattening, looping, using array_values, using just the array itself and I keep falling short.
Thanks
Nick
function cartesian() {
$_ = func_get_args();
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}
$count = call_user_func('cartesian', array($total));
print_r($count);
Your arrays already look exactly the way you want them to. array(1,3) is the same as array(0 => 1, 1 => 3) and both are an array with the value 1 at key 0 and 3 at key 1. Exactly what the debug output shows you.
It seems you just need to pass them as separate arguments to the function. E.g.:
cartesian($total[0], $total[1], $total[2])
For dynamic lengths of arrays, do:
call_user_func_array('cartesian', $total)
I believe that your $total array is multi-dimensional array with numeric indexed. So yo can try like this
$count = cartesian($total[0], $total[1], $total[2]);

if we have 5 different array how to merge them in single array in php

I have 5 different array whose structure is :-
Array ( [0] => http://www.php.net/200
)
Array ( [0] => http://www.php.net/?setbeta=1&beta=1302
)
Array ( [0] => http://www.php.net/downloads.php200
)
Array ( [0] => http://www.php.net/docs.php200
)
Array ( [0] => http://www.php.net/FAQ.php302
)
I need to merge these all in a single array whose structure would be like:-
Array ( [0] => http://www.php.net/200
[1] => http://www.php.net/?setbeta=1&beta=1302
[2] => http://www.php.net/downloads.php200
[3] => http://www.php.net/docs.php200
[4] => http://www.php.net/FAQ.php302
)
One thing i want to confirm that these arrays are forming inside a loop function and it could be of any number and also they have a single name i.e $array
Simplest is probably just array_merge().
$merged = array_merge( $ar1, $ar2, $ar3, $ar4, $ar5 );
Use array_merge.
$arr = array_merge($arr1,$arr2,$arr3,$arr4,$arr5);
Edit After seeing your comment, you are having multidimensional array.
$arr = array();
for($i = 0; $i < $old_arr; $i++) {
$arr[] = $old_arr[$i][0];
}
Use array_merge
$arr1=Array ( 0 => 'http://www.php.net/200');
$arr2=Array( 0 => 'http://www.php.net/?setbeta=1&beta=1302');
$arr3=Array( 0 => 'http://www.php.net/downloads.php200');
$merged=array_merge($arr1,$arr2,$arr3);
print_r($merged);
$newarray = array();
while ( is_array( array_get_function_here() ) )
{
$newarray = array_merge( $newarray, $array );
}
I would try that if you get the different arrays in a looping function.
The above $array is something that array_get_function_here() should return for the while loop validity check (if it returns and array, the while check runs as true). array_get_function_here() is just an example and should be some function that returns a value for $array.

Categories