Join two or more arrays of arrays - php

Suppose I have two arrays like the following:
$arr2 = array(array("first", "second"), array("third", "fourth"));
$arr3 = array(array("fifth", "sixth", "seventh"), array("eighth", "ninth"), array("tenth", "eleventh"));
And I want a result like this:
$arr4 = array("first", "second", "third", "fourth", "fifth", "sixth", "seventh","eighth", "ninth","tenth", "eleventh" );
How to do that? in PHP

What you want to is flatten and combine the arrays. There's a nice function for flattening in the comments in the PHP manual of array_values, http://www.php.net/manual/en/function.array-values.php#104184
Here's the code:
/**
* Flattens an array, or returns FALSE on fail.
*/
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
Just run this on array($arr2, $arr3).

function flatten($ar,&$res) {
if (is_array($ar))
foreach ($ar as $e) flatten($e,$res);
else
$res[]=$ar;
}
$arr2 = array(array("first", "second"), array("third", "fourth"));
$arr3 = array(array("fifth", "sixth", "seventh"), array("eighth", "ninth"), array("tenth", "eleventh"));
$arr4=array();
flatten($arr2,$arr4);
flatten($arr3,$arr4);

Related

Incrementing value of an array from another array

I have 2 arrays
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
Now I need to search in $array2 for id from $array1 and if found to increment the count value and also add to the array the one's which are not found with a count as 1 so my resulting array would be
$arr = array(array('id'=>22, 'count'=> 2), array('id'=>124, 'count'=>3), array('id'=>193, 'count'=>1));
any help would be appreciated
The current code which I tried is
if($array2){
foreach($array1 as $array){
if(in_array($array, array_column($array2, 'id'))){
$wa_array['count'] += 1;
} else {
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
} else {
foreach($array1 as $array){
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
This may be something you are looking for -
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
foreach($array1 as $key=>$digit)
{
$keyFound = array_search($digit, array_column($array2, 'id'));
if($keyFound === false)
{
array_push($array2, ['id'=>$digit, 'count'=>1]);
}
else
{
$array2[$keyFound]['count']++;
}
}
print_r($array2);
The question is not so clear, so I will go with my understanding : You need to check if values inside the first array are in the second array. If yes, increment the count value of that second array, if not, create that element with the value of 1.
This code is not tested, hope this can help find the good solution.
foreach($array1 as $value){
searchForId($value,$array2);
}
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['id'] === $id) {
$val['count'] += 1;
}else{
array_push(array('id'=>$id,'count'=>1))
}
}
return null;
}
you should loop through $array2, not $array1. Finding the value in array_column($array2, 'id') doesn't tell you the index of the array element to increment.
foreach ($array2 as &$item) {
if (in_array($item['id'], $array1)) {
$item['count']++;
}
}
Note that you have to use &$item to make this a reference to the original array element, so that modifying it will update $array2. Otherwise, $item would be a copy of the array element.
If $array1 is large, it would be better to convert it to an associative array so you can test membership more efficiently.
$array1_assoc = array_flip($array1);
Then the test in the loop becomes:
if (isset($array1_assoc[$item['id']]) {
Check this one. NOTE: But this has O(n^2) complexity.
$array1 = [22,193,124];
$array2 = [['id'=>22, 'count'=> 1], ['id'=>124, 'count'=>2]];
foreach ($array1 as $value) {
$isFound = false;
foreach ($array2 as &$item) {
if ($value == $item['id']) {
$item['count']++;
$isFound = true;
continue;
}
}
if ($isFound == false) {
$array2 [] = ['id'=>$value, 'count'=> 1];
}
}
var_dump($array2);

PHP comparing 2 arrays

I've stuck in some certain problem, I've got two arrays which are the output of some other methods:
$firstArray = ['Johny Mao'=>'A', 'Kate Young'=>'B', 'Adam Mink'=>'C'];
$secondArray = [
['Johny Mao','A'],
['Kate Young', 'B'],
['Adam Mink', 'C']
];
How should I change these two arrays in order two compare them?
I need to know wheter they consist the same information.
Probably I should use array_diff methods but first I need to change arrays structure to be able to compar them.
Hope expressed clearly :)
Create a new array (or modify the second array) to key/value pairs matching the first array
$newArray = array_combine(
array_column($secondArray, 0),
array_column($secondArray, 1)
);
and then do your comparison
The comments are spot on. This is the developers idea.
Without using array_diff or something:
function array_are_same($firstarray,$secondarray){
foreach ($firstarray as $key => $value) {
if (!array_key_exists($key, $secondarray)
|| $secondarray[$key] !== $value){
return false;
}
return true;
}
}
You could do something like this, assuming you don't need to check if elements in first array aren't in second array.
function areArraysEqual($firstArray, $secondArray)
{
if(count($firstArray) != count($secondArray))
{
return false;
}
foreach($secondArray as $key => $value)
{
if(!isset($firstArray[$value[0]]) || $firstArray[$value[0]] != $value[1])
{
return false;
}
}
return true;
}
$firstArray = ['Johny Mao'=>'A', 'Kate Young'=>'B', 'Adam Mink'=>'C'];
$secondArray = [
['Johny Mao','A'],
['Kate Young', 'B'],
['Adam Mink', 'C']
];
$result = areArraysEqual($firstArray, $secondArray);
var_dump($result);
Edit:
This code below should now take into account if elements in the first array aren't in the second array.
<?php
function isValueIn2dArray(&$array, $secondDimensionKey, $value)
{
foreach($array as $key => $array2)
{
if($array2[$secondDimensionKey] == $value)
{
return true;
}
}
return false;
}
function areArraysEqual($firstArray, $secondArray)
{
if(count($firstArray) != count($secondArray))
{
return false;
}
foreach($secondArray as $key => $value)
{
if(!isset($firstArray[$value[0]]) || $firstArray[$value[0]] != $value[1])
{
return false;
}
}
foreach($firstArray as $key => $value)
{
if(!isValueIn2dArray($secondArray, 0, $key))
{
return false;
}
}
return true;
}
$firstArray = ['Johny Mao'=>'A', 'Kate Young'=>'B', 'Adam Mink'=>'C'];
$secondArray = [
['Johny Mao','A'],
['Kate Young', 'B'],
['Adam Mink', 'C']
];
$result = areArraysEqual($firstArray, $secondArray);
var_dump($result);

merging overlapping array in php

I have two array like below:
$array1 = array(
[0]=>array([0]=>a_a [1]=>aa)
[1]=>array([0]=>b_b [1]=>bb)
[3]=>array([0]=>c_c [1]=>cc)
)
$array2 = array(
[0]=>array([0]=>aa [1]=>AA)
[1]=>array([0]=>bb [1]=>BB)
[3]=>array([0]=>cc [1]=>CC)
)
what i would like to merge or overlap to output like below:
$result = array(
[0]=>array([0]=>a_a [1]=>AA)
[1]=>array([0]=>b_b [1]=>BB)
[3]=>array([0]=>c_c [1]=>CC)
)
either output like below:
$result = array(
[0]=>array([0]=>a_a [1]=>aa [2]=>AA)
[1]=>array([0]=>b_b [1]=>bb [2]=>AA)
[3]=>array([0]=>c_c [1]=>cc [2]=>AA)
)
how i do this thing what is the best way any suggestion.
I don;t know which is the best way but you could do this with two loops. Example:
$result = array();
foreach($array1 as $val1) {
foreach($array2 as $val2) {
if($val1[1] == $val2[0]) {
$result[] = array($val1[0], $val1[1], $val2[1]);
}
}
}
echo '<pre>';
print_r($result);
For the first result, its easily modifiable:
$result[] = array($val1[0], $val2[1]);
you can use this function
1st output :
function my_array_merge(&$array1, &$array2) {
$result = array();
foreach($array1 as $key => &$value) {
$result[$key] = array_unique(array_merge($value, $array2[$key]));
}
return $result;
}
$arr = my_array_merge($array1, $array2);
2st output :
function my_array_merge(&$array1, &$array2) {
$result = array();
foreach($array1 as $key => &$value) {
$result[$key] = array_merge(array_diff($value, $array2[$key]), array_diff($array2[$key],$value));
}
return $result;
}

Setting a value in a multi-dimensional array using an array of keys

In relation to this question i asked earlier: Searching multi-dimensional array's keys using a another array
I'd like a way to set a value in a multi-dimensional array (up to 6 levels deep), using a seperate array containing the keys to use.
e.g.
$keys = Array ('A', 'A2', 'A22', 'A221');
$cats[A][A2][A22][A221] = $val;
I tried writing a clumsy switch with little success... is there a better solution?
function set_catid(&$cats, $keys, $val) {
switch (count($keys)) {
case 1: $cats[$keys[0]]=$val; break;
case 2: $cats[$keys[0]][$keys[1]]=$val; break;
case 3: $cats[$keys[0]][$keys[1]][$keys[2]]=$val; break;
etc...
}
}
try this:
function set_catid(&$cats, $keys, $val) {
$ref =& $cats;
foreach ($keys as $key) {
if (!is_array($ref[$key])) {
$ref[$key] = array();
}
$ref =& $ref[$key];
}
$ref = $val;
}
function insertValueByPath($array, $path, $value) {
$current = &$array;
foreach (explode('/', $path) as $part) {
$current = &$current[$part];
}
$current = $value;
return $array;
}
$array = insertValueByPath($array, 'A/B/C', 'D');
// => $array['A']['B']['C'] = 'D';
You can obviously also use an array for $path by just dropping the explode call.
You should use references.
In the foreach we're moving deeper from key to key. Var $temp is reference to current element of array $cat. In the end temp is element that we need.
<?php
function set_catid(&$cats, $keys, $val) {
$temp = &$cats;
foreach($keys as $key) {
$temp = &$temp[$key];
}
$temp = $val;
}
$cats = array();
$keys = Array ('A', 'A2', 'A22', 'A221');
set_catid($cats, $keys, 'test');
print_r($cats);
?>

return monodimensional-array from multidimensional

I have a multidimensional array:
$array=array( 0=>array('text'=>'text1','desc'=>'blablabla'),
1=>array('text'=>'text2','desc'=>'blablabla'),
2=>array('text'=>'blablabla','desc'=>'blablabla'));
Is there a function to return a monodimensional array based on the $text values?
Example:
monoarray($array);
//returns: array(0=>'text1',1=>'text2',2=>'blablabla');
Maybe a built-in function?
This will return array with first values in inner arrays:
$ar = array_map('array_shift', $array);
For last values this will do:
$ar = array_map('array_pop', $array);
If you want to take another element from inner array's, you must wrote your own function (PHP 5.3 attitude):
$ar = array_map(function($a) {
return $a[(key you want to return)];
}, $array);
Do it like this:
function GetItOut($multiarray, $FindKey)
{
$result = array();
foreach($multiarray as $MultiKey => $array)
$result[$MultiKey] = $array[$FindKey];
return $result;
}
$Result = GetItOut($multiarray, 'text');
print_r($Result);
Easiest way is to define your own function, with a foreach loop. You could probably use one of the numerous php array functions, but it's probably not worth your time.
The foreach loop would look something like:
function monoarray($myArray) {
$output = array();
foreach($myArray as $key=>$value) {
if( $key == 'text' ) {
$output[] = $value;
}
}
return $output;
}
If the order of your keys never changes (i.e.: text is always the first one), you can use:
$new_array = array_map('current', $array);
Otherwise, you can use:
$new_array = array_map(function($val) {
return $val['text'];
}, $array);
Or:
$new_array = array();
foreach ($array as $val) {
$new_array[] = $val['text'];
}
Try this:
function monoarray($array)
{
$result = array();
if (is_array($array) === true)
{
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value)
{
$result[] = $value;
}
}
return $result;
}
With PHP, you only have to use the function print_r();
So --> print_r($array);
Hope that will help you :D

Categories