Merging multiple PHP arrays - php

My problem is this: I'm creating an Array in order to store these 2 types of 'refinement'. However, what is happening is as the information is collected from the database, each 'refinement' is assigned to it's own specific entry when the arrays are created within the while loop.
while($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
etc...
}
So for instance, the 1st array would be a reference to 'Die Hard' and the 2nd, 'Breaking Bad' and the 3rd, 'Greys Anatomy'. What i'm trying to achieve is to merge them into 1 single array.
Array
(
[genreType] => Action
[mediaType] => Film
)
Array
(
[genreType] => Action
[mediaType] => TV
)
Array
(
[genreType] => Drama
[mediaType] => TV
)
Thanks for any help.

Try looking at this, http://php.net/manual/en/function.array-merge.php
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
OUTPUT
Array (
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)

Why can't you just use array_merge? from the php docs http://php.net/manual/en/function.array-merge.php

while{$row...
{
$movies[] = $row;
//OR
$tmp['genreType'] = $row['genre'];
//and the like.....
$movies[] = $tmp;
}
Resulting in
$movies = array(
array(
"title"=>"Die Hard",
"genreType"=>"Action",
"mediaType"=>"Film"
),
array(
"title"=>"some other movie",
"genreType"=>"Comedy",
"mediaType"=>"TV"
)
);
like this?

Related

Joining two arrays in an order

I have two arrays that i need to join and then return at the end of the function. Here is what is in both arrays is the style of print_r()
Array 1:
Array (
[0] => Main Door
[1] => Clock
[2] => Production corridor
[3] => Warehouse Corridor
[4] => Production corridor
[5] => Warehouse Corridor
[6] => Production corridor
)
Array 2:
Array (
[0] => 08:04:14
[1] => 08:04:29
[2] => 08:07:10
[3] => 08:36:34
[4] => 08:40:40
[5] => 08:58:33
[6] => 09:00:58
)
So these two arrays correspond with each other so Main Door out of the first array goes with 08:04:14 out of the second array and so on, so what would be the best way to put these two arrays in to one where they are joined like that?
if you want results like array('Clock', '08:04:29'):
array_combine($a1, $a2);
otherwise:
$new = array();
foreach($a1 as $k => $v) {
$new[$k] = array($v, $a2[$k]);
}
eg:
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
and go through the below link for more examples,
http://php.net/manual/en/function.array-merge.php
This should do:
$a1 = array(0 => 'main door', 1 => 'clock');
$a2 = array(0 => '08:04:14', 1 => '08:04:29');
$length = count($a1);
$a3 = array();
for ($i = 0; $i < $length; ++$i) {
$a3[] = array($a1[$i], $a2[$i]);
// if you want to keep the indexes the same, use $a3[$i] instead
}
var_dump($a3);
Example
Using that code you can access the data like this:
$desc = $a3[0][0]; // main door
$time = $a3[0][1]; // 08:04:14

Handling multi-dimensional PHP Array

I have arrays of fonts with their name and weight e.g.
print_r($fontarray1);
Array (
[font] => Open+Sans
[weight] => normal
)
print_r($fontarray2);
Array (
[font] => Open+Sans
[weight] => bold
)
print_r($fontarray3);
Array (
[font] => Lato
[weight] => bolditalic
)
I have many arrays of fonts $fontarray1, $fontarray2, $fontarray3.. I want to make one final array of fonts and their weights.. for example, if "Open+Sans" is already in the final array, it should not be added, but if "Open+Sans" is in final Array with a different "weight" then only the "weight" should be added alongwith the "Open+Sans" key.. the expected result should be something like:
Array (
[font] => Oen+Sans
[weight] => Array (
[0] => normal
[1] =>bold
)
[font] => Lato
[weight] => Array (
[0] => bolditalic
)
)
I tried something like below, but confused on how to add another array within one array..:
$final_arr = Array();
if (!in_array($fontarray1['font'], $final_arr)) {
$final_arr []= $fontarray1['font'];
} else {
// already in array, lets check font weight
}
}
any help or thought would be highly appreciated. cheers
First
Use array_merge
<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>
Second
Use array_unique
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Look` like structure like this can be usefull for you:
Array(
"fontName" => Array(
[weight] => Array(
[0] => "normal"
)
)
)
And your function would be like
$final_arr = Array();
$fontName = $fontarray1['font'];
$fontWeight = $fontarray1['weight'];
if (!isset($final_arr[$fontName])) {
$final_arr[$fontName] = array('weight' => $fontWeight);
} else {
$final_arr[$fontName]['weight'][] = $fontWeight;
}
You're just trying to add $fontarray1 to $final_arr?
$final_arr[] = $fontarray1
Creating a multidimensional array:
$theArray = array();
$theArray[] = array('key1'=>'val1', 'key2'=>'val2'); // creates a subarray

php array find duplicates, sum them up & delete duplicates

i have an array:
Array
(
[0] => Array
(
[setid] => 2
[income] => 100
)
[1] => Array
(
[setid] => 2
[income] => 120
)
[2] => Array
(
[setid] => 3
[income] => 700
)
)
i need to find entrys with the same setid, sum their income up and delete duplicate entrys - in the end it should look like this:
Array
(
[0] => Array
(
[setid] => 2
[income] => 220
)
[1] => Array
(
[setid] => 3
[income] => 700
)
)
does someone know a sophosticated solution for my problem or do i have to take the long road and do every step manually?
thanks and greetings
Just create a new array which you make fast adressable by using the setid as key. And reindex the array at the end.
$result = array();
foreach ($array as $val) {
if (!isset($result[$val['setid']]))
$result[$val['setid']] = $val;
else
$result[$val['setid']]['income'] += $val['income'];
}
$result = array_values($result); // reindex array
This should work:
$values = array();
foreach($array as $val) {
if(isset($values[$val['setid']])) {
$values[$val['setid']] += $val['income'];
} else {
$values[$val['setid']] = $val['income'];
}
}
//all values are now in $values array, keys are setid and values are income
Write your own function, that's no long road at all.
$result = array_reduce($originalArray, function($memo, $item){
isset($memo[$item['setid']])
? $memo[$item['setid']] = $item['income']
: $memo[$item['setid']] += $item['income'];
return $memo;
}, []);
You should use the array_unique function that php's official site offers.
An example:
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Output:
Array
(
[a] => green
[0] => red
[1] => blue
)
To sum the duplicated values you can use the array_count_values function:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output would be:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)

php building / populating an Array of Arrays

I have seen alot of tutorial on how to get the data out of a 2D array but I need to build one similar to this and I have not found any logic I can follow:
$array = array("socks" => array("blue", "red", "green"),
"shirts" => array("small", "medium", "large"));
I cant seem to figure out the logic to even start the code....
for each clothingType // I did this
get options // I did this
for each option //I did this
add to the clothingOption Array //... help!
Im only stuck on the building of the clothingOption 2D Array
could it be someting like
foreach clothingType as $kClothes =>VClothes
get Options
for each Options as $kOptions =>$VOption
$array[$VClothes][]= $VOption
Thanks and I hope this is not too vague....
How about the following?
<?php
function getMe($type) {
//do some processing and construct array
return array('a','b','c');
}
$myTypes = array('type1','type2','type3');
$answer = array();
foreach($myTypes as $val) {
$answer[$val] = getMe($val);
}
print_r($answer);
?>
Output:
Array ( [type1] => Array ( [0] => a [1] => b [2] => c ) [type2] => Array ( [0] => a [1] => b [2] => c ) [type3] => Array ( [0] => a [1] => b [2] => c ) )
maybe (sorry for errors - by hand):
//$array = array("socks" => array("blue", "red", "green"),
// "shirts" => array("small", "medium", "large"));
$types = array('socks', 'shirts');
$socks = array("blue", "red", "green");
$shirts = array("small", "medium", "large");
$array = array();
foreach ($types as $type) {
foreach($$type as $cloth) {
$array[$type][] = $cloth;
}
}
print_r($array);

PHP: Intersect two arrays and get the values of both

So I am a bit stuck here, I can do it with foreach loop but I want to find a cleverer way of doing it.
Update: There was something that I've missed in the question. The arrays may come in random order and in different length thus having different keys. Examples below updated.
Here is the case:
Array1
array (
slug1 => England,
slug2 => France,
slug3 => Italy,
slug4 => Germany,
)
Array2
array (
slug2 => 215,
slug1 => 168,
slug4 => 55,
slug5 => 149,
slug3 => 40,
slug6 => 137,
)
I want to intersect those arrays and build new one which has the following elements:
array (
168 => England,
215 => France,
40 => Italy,
55 => Germany,
)
Note: elements are not ordered though that could be achieved easily.
Answer to Original Question
You can use array_combine it creates an array by using one array for keys and another for its values
$array1 = array(
"slug1" => "England",
"slug2" => "France",
"slug3" => "Italy",
"slug4" => "Germany");
$array2 = array(
"slug1" => "168",
"slug2" => "215",
"slug3" => "40",
"slug4" => "55");
$final = array_combine($array2, $array1);
echo "<pre>";
print_r($final);
Output
Array
(
[168] => England
[215] => France
[40] => Italy
[55] => Germany
)
See Live Demo
Answer to Updated Question
Update: There was something that I've missed in the question. The arrays may come in random order and in different length thus having different keys. Examples below updated.
$array1 = array(
"slug1" => "England",
"slug2" => "France",
"slug3" => "Italy",
"slug4" => "Germany");
$array2 = array (
"slug2" => 215,
"slug1" => 168,
"slug4" => 55,
"slug5" => 149,
"slug3" => 40,
"slug6" => 137);
$final = customCombine($array2, $array1);
echo "<pre>";
print_r($final);
Output
Array
(
[215] => France
[168] => England
[55] => Germany
[40] => Italy
)
Function Used
function customCombine($keys, $arr) {
$t = array();
foreach ( $keys as $k => $val ) {
isset($arr[$k]) and $t[$val] = $arr[$k];
}
return $t;
}
Baba's answer should work fine for you, but here's an interesting way to deal with different key orders between both arrays and/or different sizes.
// get values from $array2 in the order in which they appear in $array1
// whereby the array keys are used to match them
$keys = array_intersect_key($array2, $array1);
// create a new array with the keys found in the previous step and
// another array_intersect_key() to only select the matching items
// from $array1
array_combine($keys, array_intersect_key($array1, $keys));
It also makes sure that array_combine() works with same sized arrays; the size of $array2 is the output size.
To expand Jack's answer, as it might combine the arrays in the order they're constructed in and not the order the keys are matching:
Array
(
[215] => England
[168] => France
[55] => Italy
[40] => Germany
)
Some intermediate data juggling can sort it out (and it works no matter which array is shorter):
$array1 = array(
'slug1' => 'England',
'slug2' => 'France',
'slug3' => 'Italy',
'slug4' => 'Germany'
);
$array2 = array (
'slug2' => 215,
'slug1' => 168,
'slug4' => 55,
'slug5' => 149,
'slug3' => 40,
'slug6' => 137
);
$keys = array_intersect_key($array2, $array1);
ksort($keys);
$intersect = array_intersect_key($array1, $keys);
ksort($intersect);
$final = array_combine($keys, $intersect);
print_r($final);
Outputs
Array
(
[168] => England
[215] => France
[40] => Italy
[55] => Germany
)
use array_combine()
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
http://in1.php.net/array-combine
I found the best solution for me:
http://eval.in/3578
<?php
$array1 = array("slug1" => "England","slug2" => "France","slug3" => "Italy","slug4" => "Germany");
$array2 = array("slug1" => "168","slug2" => "215","slug3" => "40","slug4" => "55", "slug5" => "178");
ksort($array1);
ksort($array2);
$test1 = array_intersect_key($array1, $array2);
$test2 = array_intersect_key($array2, $array1);
$final = array_combine($test2, $test1);
print_r($final);
?>

Categories