Merge the values of two or more arrays in php - php

Someone could be so nice to tell me how to do the following with 2 ore more arrays in PHP:
array 1 (a,b,c,d)
array 2 (1,2,3,4)
I would like to merge the two arrays in an unique array with the merged values:
Result: unique array (a-1,b-2,c-3,d-4).
Is there any function that does so? I could not find anything in the forum either on the web.
Thanks for all your answers but I guess that my arrays are a bit more structured because I need the final result for a dropdown field.
Now I have these 2 arrays:
$array1[] = array( 'text' => $hospital['value'], 'value' => $hospital['value'] );
$array2[] = array( 'text' => $company['value'], 'value' => $company['value'] );
I want to have a final array that contains: Hospital1 - Company1, Hospital2 - Company2, Hospital3 - Company3, etc..
Thanks

You can use array_map:
$result = array_map(function ($item1, $item2) {
return "$item1-$item2";
}, $array1, $array2);
Here is working demo.

You would have to create a loop to do this manually. it might look something like the following:
$a = array(a,b,c,d);
$b = array(1,2,3,4);
$c = array(); //result set
if(count($a) == count($b)){ // make sure they are the same length
for($i = 0; $i < count($a); $i++){
$c[] = $a[$i]."-".$b[$i];
}
}
print_r($c);

If i understand right, you can use array_combine where array 1 will be the key and array 2 the value.
Example usage:
$a = array(1,2,3,4);
$b = array(a,b,c,d);
$c = array_combine($a, $b);
var_dump($c);

Related

php array of arrays to 1D array not getting properly as expected

I am reading value from CMD which is running a python program and my output as follows:
Let as assume those values as $A:
$A = [[1][2][3][4]....]
I want to make an array from that as:
$A = [1,2,3,4....]
I had tried as follows:
$val = str_replace("[","",$A);
$val = str_replace("]","",$val);
print_r($val);
I am getting output as:
Array ( [0] => 1 2 3 4 ... )
Please guide me
try this
// your code goes here
$array = array(
array("1"),
array("2"),
array("3"),
array("4")
);
$outputArray = array();
foreach($array as $key => $value)
{
$outputArray[] = $value[0];
}
print_r($outputArray);
Also check the example here https://ideone.com/qaxhGZ
This will work
array_reduce($a, 'array_merge', array());
Multidimensional array to single dimensional array,
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($A));
$A = iterator_to_array($it, false);
But, if $A is string
$A = '[[1][2][3][4]]';
$A = explode('][', $A);
$A = array_map(function($val){
return trim($val,'[]');
}, $A);
Both codes will get,
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
This function will work when you do indeed have a multidimensional array, which you stated you have, in stead of the String representation of a multidimensional array, which you seem to have.
function TwoDToOneDArray($TwoDArray) {
$result = array();
foreach ($TwoDArray as $value) {
array_push($result, $value[0]);
}
return $result;
}
var_dump(TwoDToOneDArray([[0],[1]]));
You can transform $A = [[1],[2],[3],[4]] into $B = [1,2,3,4....] using this following one line solution:
$B = array_map('array_shift', $A);
PD: You could not handle an array of arrays ( a matrix ) the way you did. That way is only for managing strings. And your notation was wrong. An array of arrays (a matrix) is declared with commas.
If you have a string like you wrote in the first place you can try with regex:
$a = '[[1][2][3][4]]';
preg_match_all('/\[([0-9\.]*)\]/', $a, $matches);
$a = $matches[1];
var_dump($a);
If $A is a string that looks like an array, here's one way to get it:
$A = '[[1][2][3][4]]';
print "[".str_replace(array("[","]"),array("",","),substr($A,2,strlen($A)-4))."]";
It removes [ and replaces ] with ,. I just removed the end and start brackets before the replacement and added both of them after it finishes. This outputs: [1,2,3,4] as you can see in this link.

Subtracting arrays to get every difference

What I have
$array1 = [1,1,1];
$array2 = [1,1];
What I'm doing:
array_diff( $array1, $array2 );
What I expected:
array(1) { 1 }
What I got
array(0) { }
How do I subtract two arrays to get every discrepancy?
Edit:
My example was incomplete, sorry.
If we also have values like this:
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
I would expect
[1,1,2,1] - [1,1,1,2] = []
array_diff_assoc() is the right way to go here. But to get your expected result you just have to sort the array first with usort() where I compare the values with strcasecmp().
So this should work for you:
<?php
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
function caseCmpSort($a, $b){
return strcasecmp($a, $b);
}
usort($array1, "caseCmpSort");
usort($array2, "caseCmpSort");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>
output:
Array ( )
use array_diff_assoc
$array1 = [1,1,1];
$array2 = [1,1];
print_r(array_diff_assoc( $array1, $array2)); // outputs Array ([2] => 1)
try it here http://sandbox.onlinephpfunctions.com/code/43394cc048f8c9660219e4fa30386b53ce4adedb
So you should check array key differences too. Have you tried array_diff_assoc()?
http://php.net/manual/en/function.array-diff-assoc.php
From manual:
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
So, it is working as expected. I am not sure what exactly You want to achieve. You cloud try, it should give You expected result in this example.
$a = [1,1,1];
$b = [1,1];
print_r(array_diff_assoc($a,$b));
Edit: Well, simple sort should solve issue from Your comment. Nothe, that this will remove information of original indexes of elements.
$a = [1,1,2,1];
$b = [1,1,1,2,1];
sort($a);
sort($b);
print_r(array_diff_assoc($a,$b));
<?php
$n = array(1,1,1);
$m = array(1,1);
$r = array_diff_assoc($n,$m);
var_dump($r);
?>

Convert a numeric array of indexes to an ordered array of elements from an associative array of objects indexed by those indexes

Note: I should be clear my desire is to do this functionally, in one statement. I can do this easily with loops but that's not what I'm interested in.
I have two arrays: a numeric array of indexes, A, and an associative array, B, of objects O indexed by the elements of array A.
I want to produce an array of O in the order of the elements of A--in other words, map the indexes into real objects, based on the associative array B.
For example:
A = [ 3, 4, 2, 1 ];
B = [ 1=>"one", 2=>"two", 3=>"three", 4=>"four" ]
I want:
[ "three", "four", "two", "one" ]
Also, incidentally I'm also curious to learn what this concept is called. It's kind of like mapping, but specifically involves indexes into another array, as opposed to a function.
$A = array(3, 4, 2, 1);
$B = array(1=>"one", 2=>"two", 3=>"three", 4=>"four");
foreach($A as $i) $R[] = $B[$i];
var_dump($R);
I am just adding a little bit, if anyone is still interested in using "array_map".
<?php
$A = array( 3, 4, 2, 1);
$B = array( 1=>"one", 2=>"two", 3=>"three", 4=>"four" );
print_r($A);echo '<br/>';
print_r($B);echo '<br/>';
function matchAtoB($sourceA, $sourceB)
{
global $B;
return $B[$sourceA];
}
$O = array_map("matchAtoB", $A, $B);
print_r($O);
?>
So the function can only receive an element of each array at a time (not the whole array) and it will loop/repeat itself automatically until all elements in the array are processed.
Cheers,
You don't need a loop, you can access the elements right away:
$three = $b[$a[0]]; // "three"
$four = $b[$a[1]]; // "four"
$two = $b[$a[2]]; // "two"
$one = $b[$a[3]]; // "one"
You could see this as a 'lazy' or 'just in time' way of accomplishing the same goal, but without the ahead cost of indexing the hash map.
If you want the array explicitly, without the additional lookup, you will need a loop.
I'm not sure if this has a name but the combination of a 'datastore' or 'hash map' combined with an ordered array of keys is not an uncommon one.
$order = array(3, 4, 2, 1);
$input = array(1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four');
Using array_map() (PHP 5.3 >)
$output = array_map(function($v) use($input) {
return $input[$v];
}, $order);
However, this is essentially the same as doing the following:
$output = array();
foreach ($order as $o) {
$output[] = $input[$o];
}
I can't honestly see a shorter way of doing this.
NullUserException posted the answer in a comment:
array_map(function ($v) use ($b) { return $b[$v]; }, $a);

How to increase by 1 all keys in an array?

What is the simplest solution to increase by 1 all keys in an array?
BEFORE:
$arr[0] = 'a';
$arr[1] = 'b';
$arr[2] = 'c';
AFTER:
$arr[1] = 'a';
$arr[2] = 'b';
$arr[3] = 'c';
You can use
$start_zero = array_values($array); /* Re-Indexing Array To Start From Zero */
And if you want to start it from index 1 use
$start_one = array_combine(range(1, count($array)), array_values($array));
Well, there's one very simple way to do it:
$arr = array('a', 'b', 'c');
array_unshift($arr, null);
unset($arr[0]);
print_r($arr);
/*
Array
(
[1] => a
[2] => b
[3] => c
)
*/
Will work only for simple dense arrays, of course.
And this is most untrivial (yet both a one-liner AND working for both dense and sparse arrays) way:
$arr = array_flip(array_map(function($el){ return $el + 1; }, array_flip($arr)));
I'm not sure why you'd want to do this, but you should just be able to loop through:
$new_array = array();
foreach($arr as $key => $value){
$new_array[$key+1] = $value;
}
$arr = $new_array;
$count = count($arr);
for($i=$count; $i>0; $i--){
$arr[$i] = $arr[$i-1];
}
unset($arr[0]);
I know this question is quite old, but I ran into a similar issue recently and came up with a nice one-liner to solve it for any type of array using an arbitrary integer as the starting key:
$array = array_combine(array_keys(array_fill($starting_index, count($array), 0)), array_values($array));
$starting_index is whatever value you want for the initial integer key, e.g. 3.
This can even be used with arrays holding complex objects, unlike the solution using array_flip and does not limit you to starting the index at 0 or 1 like some of the other solutions.
I'm not sure if this qualifies as a one liner but it is a different way of doing it
$result = array_reduce(array_keys($arr),function($carry,$key) use($arr){
$carry[$key+1] = $arr[$key];
return $carry;
},[]);

PHP - Merge two arrays (same-length) into one associative?

pretty straightforward question actually..
is it possible in PHP to combine two separate arrays of the same length to one associative array where the values of the first array are used as keys in the associative array?
I could ofcourse do this, but I'm looking for another (built-in) function, or more efficient solution..?
function Combine($array1, $array2) {
if(count($array1) == count($array2)) {
$assArray = array();
for($i=0;$i<count($array1);$i++) {
$assArray[$array1[$i]] = $array2[$i];
}
return $assArray;
}
}
array_combine($keys, $values)
PS: Click on my answer! Its also a link!
you need array_combine.
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
There’s already an array_combine function:
$combined = array_combine($keys, $values);
hello everybody i will show you how to merge 2 arrays in one array
we have 2 arrays and i will make one array from them
$data_key = array('key1','key2');
$data_value = array('val1','val2');
lets declare the main array
$main_array = array();
now let's fill it with the 2 arrays
foreach ($data_key as $i => $key) {
$main_array[$key] = $data_value[$i];
}
now let's see the result by using var_dump($main_array);
array(2) {
["key1"]=> string(4) "val1"
["key2"]=> string(4) "val2"
}
i hope that can help someone :)

Categories