Flatten 2D Array Into Separate Indexed Arrays - php

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]);

Related

Count how many times a value appears in this array?

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);

PHP: Merging arrays with the same title

I have some php arrays from a loop, all of them bearing the same name. Now I want to merge them, but it seems not to work...
Here's my loop:
while($row = mysql_fetch_row($sql1)){
$startzeit=strtotime($row[2]);
$endzeit=strtotime($row[3]);
$startzeit_format = date("Y-m-d",$startzeit);
$endzeit_format = date("Y-m-d",$endzeit);
$datearray[] = createDateRangeArray($startzeit_format,$endzeit_format);
}
This should be the merging code:
for($i = 0; $i<count($datearray); $i++)
{
$datesarray = array_merge($datearray[$i]);
}
Anyway, the manual merge works fine:
$datesarray = array_merge( $datearray[0], $datearray[1], $datearray[2], $datearray[3]);
This one leads to the desired output. However I'd like to automatize it, as the single arrays come from a database and I won't add a $datearray[4], $datearray[5] and so on, everytime there is a new entry in the mySQL..
The result of print_r($datearray):
Array (
[0] => Array ( [0] => 2014-03-08 )
[1] => Array ( [0] => 2013-09-15 )
[2] => Array ( [0] => 2013-09-21 )
[3] => Array ( [0] => 2013-10-03
[1] => 2013-10-04
[2] => 2013-10-05
[3] => 2013-10-06 )
)
What you might be looking for is to flatten the array:
$datesarray = call_user_func_array('array_merge', $datearray);
It's identical to how you were manually merging together the array items.
See also: call_user_func_array()
You could also do this inside the loop with a simple loop:
$datesarray = array();
while ($row = mysql_fetch_row($sql1)) {
// ...
foreach (createDateRangeArray($startzeit_format,$endzeit_format) as $item) {
$datesarray[] = $item;
}
}
You are merging a single array to nothing.
$newArray = array_merge($array, $array)
Merges those two arrays but you are doing
$array = array_merge($datearray[$i]);
In affect, you are creating an array from one key of an array.

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.

remove uncommon values in php array

Hello all,
Array (
[0] => Array ( [id] => 242)
[1] => Array ( [id] => 24)
[2] => Array ( [id] => 234)
[3] => Array ( [id] => 244)
)
Array (
[0] => 24
[1] => 242
[2] => 244
)
When I used print_r(), I got above two arrays. Now, I need to filter two arrays and get uncommon values so my output will be 234
I would guess you mean array_diff, which returns you the set of elements that only exists in one of the arrays. You might have to run it twice however, if you don't know which array is the superset:
$diff = array_merge(array_diff($a1, $a2), array_diff($a2, $a1));
Oh and if the first array is nested like that, convert it first into a value list with $a1 = array_map("current", $a1) or something.
do a a foreach to go through the array, and then use something like in_array to do a test to see if any of the keys within the first array exists
$array3 = array();
foreach ($array1 as $v)
{
if !(in_array($v['ID'], $array2))
{
$array3[] = $v;
}
}
$array3 = array_unique($array3);
$array3 will return a list of non existant ID's (that didn't exist in $array2)
create two arrays with simply all the values in them, and then do
$arrayResult = $array1;
foreach($array1 as $id => $val) {
if !isset($array2[$id]) {
$arrayResult[] = $id;
}
}
foreach($array2 as $id => $val) {
if !isset($array1[$id]) {
$arrayResult[] = $id;
}
}
and then $arrayResult will have all uncommon values!

How to calculate/generate a string with all possible values in an array?

This is driving me nuts but I've been struggling with this all noon now (im in GMT+2;)).
I want to do a fairly (I believed but realized it turned out otherwise..) simple task.
Lets say I have an array which looks like this:
Array
(
[0] => Array
(
[OptionID] => 8748
[Values] => Array
(
[0] => 11614
[1] => 11615
)
)
[1] => Array
(
[OptionID] => 8749
[Values] => Array
(
[0] => 11616
[1] => 11617
)
)
)
This array is for generating all possible options with a product. Lets say OptionID 8748 means 'Size' and the Values in that array are 'L' & 'XL'. OptionID 8749 could be 'Color' with Values 'Red' and 'Black'.
I want to achieve the simple task to get the four unique combinations of that product in a string like:
11614+11616
11614+11617
11615+11616
11615+11617
But then, with a different product there could be a third product option, so it should be able to work arround with an unlimited depth.
basically
$result = array_cartesian(array_pluck($a, 'Values'));
and here are the helper functions:
function array_pluck($a, $key) {
$r = array();
foreach($a as $v)
$r[] = $v[$key];
return $r;
}
function array_cartesian($_) {
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = array_cartesian($_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}

Categories