I have 2 arrays:
array1 :
[0]=>
string(10) "AAAAAAAAAAA"
[1]=>
string(10) "BBBBBBBBBBB"
...
and array2:
[0]=>
float(0)
[550]=>
float(55)
...
I need a result like this:
"AAAAAAAAAAA" : 0 : 0
"BBBBBBBBBBB" : 550: 55
...
i.e. how to combine the arrays. How do i get that?
suppose you two arrays have the same length,
$keys = array_keys($array1);
$values = [];
foreach($array2 as $k=>$v)
{
$values[] = $k.':'.$v;
}
$result = array_combine($keys, $values);
The result you want is not clear... if each rows are just a string, this should work :
$a = [
0 => "AAAAAAAAAAA",
1 => "BBBBBBBBBBB"
];
$b = [
0 => (float) 0,
550 => (float) 55
];
$result = array_map(
function($v1, $v2, $v3) {
return "$v1 : $v2 : $v3";
},
$a, array_keys($b), $b
);
var_dump($result);
Related
I have an array:
$a = [
"g41" => 1,
"g44" => 2,
"g53" => 3
];
And another array is:
$list = [
40,
41,
44,
46,
53
];
How to combine these arrays by partial key matches to produce the following results?
$result = [
"41" => 1,
"44" => 2,
"53" => 3,
"40" => null,
"46" => null
];
Iterate $list array and check for the key in the other $a array:
$a = array("g41" => 1, "g44" => 2, "g53" => 3);
$list = array(40, 41, 44, 46, 53);
$result = [];
foreach ($list as $key) {
$result[$key] = $a["g$key"] ?? null;
}
var_dump($result);
Output:
array(5) {
[40]=> NULL
[41]=> int(1)
[44]=> int(2)
[46]=> NULL
[53]=> int(3)
}
since you want to the result sequence follow $a, you may need to unset $list, and push remaining lists to $result
sample code as below:
<?php
$a=["g41"=>1,"g44"=>2,"g53"=>3];
$list=[40,41,44,46,53];
$result =[];
foreach($a as $key => $value){
$new_key = substr($key,1); //remove first character, if only you first key always single char, else you may use your own method to extract key
if(in_array($new_key,$list)){
$result[$new_key] = $value;
unset($list[array_search($new_key, $list)]);//remove used key
}
}
//push remaining as null
foreach($list as $v){
$result[$v] = null;
}
print_r($result);
write your custom script
$result = [];
foreach($a as $key => $value) $result[trim($key, 'g')] = $value;
foreach($list as $key) if (!isset($result[strval($key)]) $result[strval($key)] = null;
Loop the $list array
Check if the list value (prepended with g) exists in the $a array. If so, push it with the desired numeric key into the result array; if not, push it into an alternative array with the desired numeric key and the default value of null.
When finished iterating, append the data from the alternative array to the result array.
This will properly filter your data, apply the expected default values and sort the output exactly as requested.
Code: (Demo)
foreach ($list as $v) {
if (isset($a["g$v"])) {
$result[$v] = $a["g$v"];
} else {
$extra[$v] = null;
}
}
var_export(
array_replace($result ?? [], $extra ?? [])
);
I am using ?? [] to fallback to an empty array in case either of the arrays are never declared (never receive any elements).
It looks like what you want to do first is transform the keys in array $a. Then use your $list of keys to populate null values where none are present in $a.
$aKeys = preg_replace('/\D/', '', array_keys($a));
$a = array_combine($aKeys, $a);
$defaultList = array_fill_keys($list, null);
$list = array_merge($defaultList, $a);
I need to merge multiple arrays into one where a specific key & its value are same. Here is the Sample_Array1
array(n) {
[0]=> array {
["a"]=> "m1"
["b"]=> "x2"
}
[1]=> array {
["a"]=> "n1"
["b"]=> "y2"
} ....
Sample_Array2 with one common key & other different ones.
array(n) {
[0]=> array {
["b"]=> "x2"
["c"]=> "p1"
}
[1]=> array {
["b"]=> "x2"
["d"]=> "q1"
}
[2]=> array {
["b"]=> "y2"
["e"]=> "r1"
} ....
Need to merge / append Sample_Array2 to Sample_Array1 where key-"b" & its value are same. The expected output:
array(n) {
[0]=>
array(2) {
["a"]=> "m1"
["b"]=> "x2"
["c"]=> "p1"
["d"]=> "q1"
}
[1]=>
array(2) {
["a"]=> "n1"
["b"]=> "y2"
["e"]=> "r1"
} ....
I have tried so many similar questions but couldn't find the exact result.
PHP merge arrays with a condition The answer given on this link is not solving the purpose, its making different array for each new key, while I need to append the new keys in one array.
This should work, assuming you have the "b" index in all sub arrays.
$array1 = array();
$array1[] = array("a" => "m1", "b" => "x2", "c" => null);
$array1[] = array("a" => "n1", "b" => "y2");
$array2 = array();
$array2[] = array("b" => "x2", "c" => "p1");
$array2[] = array("a" => null, "b" => "x2", "d" => "q1");
$array2[] = array("b" => "y2", "e" => "r1");
function merge_on_key($array1, $array2, $key) {
$result_array = array();
foreach($array1 as $key1 => $sub_array1) {
$merged_array = array();
$sub_array1 = array_filter($sub_array1);
foreach($array2 as $key2 => $sub_array2) {
$sub_array2 = array_filter($sub_array2);
if($sub_array1[$key] == $sub_array2[$key]) {
$merged_array = array_merge($sub_array1, $sub_array2, $merged_array);
unset($array2[$key2]);
}
}
if (!empty($merged_array)) {
$result_array[] = $merged_array;
}
}
return array_merge($result_array, $array2);
}
$final_array = merge_on_key($array1, $array2, "b");
print_r($final_array);
In case you have to match the "b" index within the $array1 itself too, then simply use it twice:
$array1 = merge_on_key($array1, $array1, "b");
$final_array = merge_on_key($array1, $array2, "b");
i really have no idea what you want to achieve here - but based on your description the following code works
$arrA = [
0 =>
[
'a' => 'm1',
'b' => 'x2'
],
1 =>
[
'a' => 'n1',
'b' => 'y2'
]
];
$arrB = [
0 =>
[
'b' => 'x2',
'c' => 'p1',
],
1 =>
[
'b' => 'x2',
'd' => 'q1',
],
2 =>
[
'b' => 'y2',
'e' => 'r1',
],
];
foreach($arrB AS $arrData)
{
foreach($arrData AS $key => $val)
{
if ((isset($arrData['a']) && $arrData['a'] == $arrA[0]['a']) || (isset($arrData['b']) && $arrData['b'] == $arrA[0]['b']))
{
$arrA[0][$key] = $val;
}
elseif ((isset($arrData['b']) && $arrData['b'] == $arrA[1]['a']) || (isset($arrData['b']) && $arrData['b'] == $arrA[1]['b']))
{
$arrA[1][$key] = $val;
}
}
}
print_r($arrA);
Created the arrays similar to yours. $new_array is the resultant array that you are looking for.
$a=array();
$a[0]=array('a'=>'m1', 'b'=>'x2');
$a[1]=array('a'=>'n1', 'b'=>'y2');
$b=array();
$b[0]=array('b'=>'x2', 'c'=>'p1');
$b[1]=array('b'=>'x2', 'd'=>'q1');
$b[2]=array('b'=>'y2', 'e'=>'r1');
foreach($a as $row){
//echo '<pre>'; print_r($row);
foreach($b as $c=>$row1){
//echo '<pre>'; print_r($row1);echo $c;die;
if($row['b']==$row1['b']){
$new_array[]=array_merge($row, $row1);
}
}
}echo '<pre>'; print_r($new_array);
// Gather all values of b from both arrays
$all_b = array_unique(array_merge(array_column($arr1, 'b'), array_column($arr2, 'b')));
$res = [];
// For each b value
foreach($all_b as $b) {
$temp = [];
// Scan the arrays for items with the same b value
foreach($arr1 as $a1) {
if ($a1['b'] == $b) $temp = array_merge($temp, $a1);
}
foreach($arr2 as $a2) {
if ($a2['b'] == $b) $temp = array_merge($temp, $a2);
}
// Save them to new array
$res[] = $temp;
}
print_r($res);
demo on eval
This question already has answers here:
PHP: Set the values of one array to another array
(7 answers)
Closed 1 year ago.
Imagine I have an array containing the following values:
$indexes = [ 'Hello' , 'Hoi', 'Ola' , 'Shalom' , 'Salaam'];
Furthermore I also have an incomplete array:
$values = ['Hello' => 2, 'Ola' => 20 ];
How can I merge these arrays to get a result displaying all indexes with their values, and 0 when no value is found?
$desiredResult = [
'Hello' => 2,
'Hoi' => 0,
'Ola' => 20 ,
'Shalom' => 0,
'Salaam' => 0
]
$indexes = [ 'Hello' , 'Hoi', 'Ola' , 'Shalom' , 'Salaam'];
$values = ['Hello' => 2, 'Ola' => 20 ];
$default = array_combine($indexes, array_fill(0, count($indexes), 0));
$result = array_replace($default, $values);
var_dump($result);
The result would be:
array(5) {
["Hello"]=>
int(2)
["Hoi"]=>
int(0)
["Ola"]=>
int(20)
["Shalom"]=>
int(0)
["Salaam"]=>
int(0)
}
You can use built-in functions (see other answers), but you can of course also loop yourself.
function addKeys(&$arr, $keys, $value = 0) {
foreach ($keys as $key) {
if (!array_key_exists($key, $arr)) {
$arr[$key] = $value;
}
}
return $arr;
}
Try it online!
You can use array_merge and array_combine, live demo.
$disiredResult = array_merge(
array_combine($indexes, array_fill(0, count($indexes), 0)), $values
);
The function you're looking for is array_combine which works like array_combine($indexes, $values)
I have an array that looks like this:
a 12 34
b 12345
c 123456
So the array looks like
$array[0] = "a 12 34"
$array[1] = "b 12345"
$array[2] = "c 123456"
I am trying to create an associative array such that
[a] => 12 34
[b] => 12345
[c] => 123456
Can I possibly split the array into two, one for containing "a, b, c" and another for their contents and use the array_combine()? Or are there any other ways?
You can do that within a loop like the snippet below demonstrates. Quick-Test here:
$array = array("a 12 34", "b 12345", "c 123456");
$array2 = array();
foreach($array as $data){
preg_match("#([a-z])(\s)(.*)#i", $data, $matches);
list(, $key, $space, $value) = $matches;
$array2[$key] = $value;
}
var_dump($array2);
// YIELDS::
array(3) {
["a"]=> string(5) "12 34"
["b"]=> string(5) "12345"
["c"]=> string(6) "123456"
}
Or using a Blend of array_walk() and array_combine() which can be Quick-Tested Here.
<?php
$array = array("a 12 34", "b 12345", "c 123456");
$keys = array();
array_walk($array, function(&$data, $key) use (&$keys){
$keys[] = trim(preg_replace('#(\s.*)#i', '', $data));;
$data = trim(preg_replace('#(^[a-z])#i', '', $data));
});
$array = array_combine($keys, $array);
var_dump($array);;
// YIELDS::
array(3) {
["a"]=> string(5) "12 34"
["b"]=> string(5) "12345"
["c"]=> string(6) "123456"
}
You can do it without any difficulty :) A simple loop is possible to do it.
Create new array
Lopp on each row
Split each data (explode(' ', $row, 2), strstr, substr, ...) ?
Put data on your new array $array[$key] = $value;
You could use a combination of array_map, array_column and array_combine:
$array = array_map(function ($v) { return explode(' ', $v, 2); }, $array);
$array = array_combine(array_column($array, 0), array_column($array, 1));
What I need is really simple:
I have two arrays like that:
<?php
$a1 = [1,2,3];
$a2 = [2,3,4];
I need to combine them so that the result is:
$result = [1,2,3,4];
I've tried array_merge but the result was [1,2,3,2,3,4]
You can find an answer to this here: Set Theory Union of arrays in PHP
By expanding on your current method. You can call array_unique and sort on the resulting array.
$a = [1,2,3];
$b = [2,3,4];
$result = array_merge($a, $b);
$result = array_unique($result);
sort($result);
This will result in:
array(4) {
[0] = int(1) 1
[1] = int(1) 2
[2] = int(1) 3
[3] = int(1) 4
}
function merges(/*...*/){
$args=func_get_args();
$ret=array();
foreach($args as $arg){
foreach($arg as $key=>$v)
{
$ret[$key]=$v;
}
}
return $ret;
}
untested, but i guess this would work.. will delete all duplicate keys and return the last key/value pair it found of duplicates
This might be what you are looking for
$result = $a1 + $a2 //union operation
reference
Array Operations
Example
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);
Ouput
Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}