PHP: Merging arrays with the same title - php

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.

Related

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

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.

How to get rid of the indexed count of arrays within an array in PHP

Hello I have an array that consists of two other arrays within it using the following code:
foreach($relations as $rel){
$data[$i]["relationTo"] = $rel["name"];
$data[$i]["relation"] = $rel["relation"];
$i = $i+1;
}
foreach($relations as $rel){
$children[$i]["id"] = $rel["id2"];
$children[$i]["name"] = $rel["sname"];
$children[$i]["data"] = $data;
$i = $i+1;
}
foreach($relations as $rel){
$relationArray[$i]["id"] = $rel["id"];
$relationArray[$i]["name"] = $rel["name"];
$relationArray[$i]["children"] = $children;
$i = $i+1;
}
When I print this out using:
print_r($relationArray);
It prints the following:
Array ( [2] => Array ( [id] => 4 [name] => Albaraa [children] =>
Array ( [1] => Array ( [id] => 5 [name] => Sadi [data] =>
Array ( [0] => Array ( [relationTo] => Albaraa [relation] => Father ) ) ) ) ) )
I am using json_encode and I need it to be output in json a certain way not including the indexed count of arrays in the beginning...the json output when I use:
echo json_encode($relationArray);
is like this currently:
{"2":{"id":"4","name":"Albaraa","children":
{"1":{"id":"5","name":"Sadi","data": [{"relationTo":"Albaraa","relation":"Father"}]}}}}
With the "2" and "1" in front of what the first 2 arrays are...which is not what I am trying to achieve which would be like this:
{"id":"4","name":"Albaraa","children":
{"id":"5","name":"Sadi","data": [{"relationTo":"Albaraa","relation":"Father"}]}}}}
Any help will be much appreciated!
Several solutions
1) Do not enter values by [$i], prepare new complete inner array and put it inside with array_push
2) If you still want to do this way you can extract just the values:
print_r(json_encode(array_values($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!

Categories