array_combine empty values - php

One array is 35 elements (mysql column names)
Array ( [1] => ID...)
second is only few elements:
Array ( [1] => 63 [2] => REF213211 [3] => aaa [7] => Warszawa [8] => Wola [12] => 100 [14] => 1 [15] => 100 [35] => 1 )
I need to combine first array as keys for second array
Please help

Example:
$header = ["a", "b", "c"];
$values = array_combine($header, array_fill(0,count($header),null));
Result:
array(3) {
'a' => NULL
'b' => NULL
'c' => NULL
}

You could use a simple foreach like this:
$combined = array();
foreach ($keys as $index => $key) {
$combined[$key] = isset($values[$index]) ? $values[$index] : null;
}
This will combine the keys in $keys with the values in $values. If there is no corresponding value in $values it will result in null.

if the keys are identical (seems to be in your case), it's simple:
$combined_array = array_combine( array_values($array1), array_values($array2) );
if the first array has more keys than the second array, you can generate a temporary array for array1 which has only these keys that are in array2 (intersection of keys):
$temporary = array_intersect_key( $array1, $array2 );
$combined_array = array_combine( array_values($temporary), array_values($array2) );
Regards
rbo

$newarray = Array();
foreach( $columnarray as $key => $columnname )
{
if ( isset($secondarray[$key]) ) $newarray[$columnname] = $secondarray[$key];
}

if you want to get a hash as the result, iterate over both arrays until the shortest array is completely traversed and put key/value pairs into the hash table.

https://www.php.net/manual/en/function.array-fill-keys.php
array_fill_keys(['a', 'b', 'c'], null);
Result:
array(3) {
'a' => NULL
'b' => NULL
'c' => NULL
}

Related

replace specific array value with another array values in php

my 1st array values are
Array (
[0] => abc
[1] => xyz
[2] => Other
[3] => Other
[4] => pqr )
when array contains value as Other i want to replace that with below array
Array (
[0] => lmnsa
[1] => asda )
I want to do this in PHP. any help guys?
First loop over the array1 and test for the value 'Other', if found replace the value with your array2
Note the use of &$a to make the $a from the foreach loop a reference, so that it can be used to replace the original array occurance and not a copy of the array which woudl have been the result without the use of the &
$array1 = Array ( "abc","xyz","Other", "Other", "pqr" );
$array2 = Array ( "lmnsa", "asda" );
foreach ($array1 as &$a) {
if ( $a == 'Other') {
$a = $array2;
}
}
print_r($array1);
The RESULT
Array
(
[0] => abc
[1] => xyz
[2] => Array
(
[0] => lmnsa
[1] => asda
)
[3] => Array
(
[0] => lmnsa
[1] => asda
)
[4] => pqr
)
I don't really understand what result are you looking for.
If you want to just replace elements with value 'Other' with some different value:
$newValue = 'New value instead of Other';
// $newValue = ['abc' 'def']; <-- if you want to replace string by an array. It wasn't unclear what you expect to achieve from the question.
$array = ['a', 'b', 'Other', 'c', 'Other', 'd'];
foreach ($array as $idx => $element) {
if ($element === 'Other') {
$array[$idx] = $newValue;
}
}
Or if you have an array of replacements, which must gradually replace all 'Other' values:
$array = ['a', 'b', 'Other', 'c', 'Other', 'd'];
$replacements = ['New Value 1', 'New Value 2'];
$replacementIdx = 0;
foreach ($array as $idx => $element) {
// Always check if you were not run out of replacement values
if (!isset($replacements[$replacementIdx])) {
break;
}
if ($element === 'Other') {
$array[$idx] = $replacements[$replacementIdx++];
}
}
Instead of using foreach ($array as $key => $value) you may also try to replace elements by reference (see RiggsFolly answer)
Based on your request what Yamingue stated is correct. You may need to clarify what you want. Are you attempting to say if the indexed value of the array initial array is 2 and its value is "Other" to replace it with it with the equivalent value of another array with the same index number?
Its been a while since ive done php buy lets give this a go.
$array1 = Array (
0 => "abc"
1 => "xyz"
2 => "Other"
3 => "Other"
4 => "pqr" );
$array2 = Array (
0 => "lmnsa"
1 => "asda"
2 => "thg"
3 => "ris"
4 => "slrn");
Foreach($array1 as $arr1key => $arr1val) {
If($arr1val == "Other"){
$array1[$arr1key] = $array2[$arr1key];
}
}
You may need to unset the values however as i said been a while for me. Nowbif you want to embed the 2nd array into the value of the first array where it currently says other thats another story, each language is a little different on multidimensional and nested arrays so i cant speak to it.
there are several ways to do it as needed. the first is to replace it with another array like this
`
$array1 = Array (
0 => "abc"
1 => "xyz"
2 => "Other"
3 => "Other"
4 => "pqr" );
$array2 = Array (
0 => "lmnsa"
1 => "asda" );
$array1 = $array2
`

Group associative row data based on shared column value

I have a multidimensional array like:
Array
(
[0] => Array
(
[division] => Mymensingh
[A] => 1
)
[1] => Array
(
[division] => Dhaka
[A] => 5
)
[2] => Array
(
[division] => Mymensingh
[B] => 2
[C] => 5
)
)
I need to find the rows with matching division values and merge them in one array.
From this array, I want the output as:
Array
(
[0] => Array
(
[division] => Mymensingh
[A] => 1
[B] => 2
[C] => 5
)
[1] => Array
(
[division] => Dhaka
[A] => 5
)
)
Keys in the subarrays can be different and the subarrays may have a differing number of elements.
I think it's relatively simple to just iterate through the array and continuously merge the entries separated by "division":
function mergeByDiscriminator($input, $discriminator = 'division') {
$result = [];
foreach ($input as $array) {
$key = $array[$discriminator];
$result[$key] = array_merge(
array_key_exists($key, $result) ? $result[$key] : [],
$array
);
}
return array_values($result);
}
$result = mergeByDiscriminator($input); // $input is your array
The only solution that I can think of is as below. Of course there might be other feasable solutions, but I am giving one from my end.
$array = array(
'0' => array (
'division' => 'Mymensingh',
'A' => 1
),
'1' => array (
'division' => 'Dhaka',
'A' => 5
),
'2' => array (
'division' => 'Mymensingh',
'B' => 2,
'C' => 5
),
);
$result = array();
foreach ($array as $arr) {
if (!is_array($result[$arr['division']])) $result[$arr['division']] = array();
foreach ($arr as $key => $value) {
$result[$arr['division']][$key] = $value;
}
}
echo "<pre>"; print_r($result);
The above code is giving you the desired output. Please give it a try.
Hope this helps.
This task is concisely completed with zero iterated function calls thanks to the null coalescing operator and the union operator.
Merge each iterated row with the pre-existing data in that keyed-group. If the keyed-group has not yet been encountered merge the row with an empty array.
The union operator is suitable/reliable in this case because it is writing one associative array into another associative array.
Language Construct Iteration: (Demo)
$result = [];
foreach ($array as $row) {
$result[$row['division']] = ($result[$row['division']] ?? []) + $row;
}
var_export(array_values($result));
Functional Iteration: (Demo)
var_export(
array_values(
array_reduce(
$array,
function($result, $row) {
$result[$row['division']] = ($result[$row['division']] ?? []) + $row;
return $result;
},
[]
)
)
);

Array merge with same keys

I have these three arrays:
Array
(
[1] => sadsad#fsdf.fgh
[2] => rtt#RERT.FDG
[3] => WQEWQ#fgdg.h
)
Array
(
[1] =>
[2] => 4234235
[3] =>
)
Array
(
[2] => 1
)
And I want to generate this output:
Array
(
[1] => array(
[0] => sadsad#fsdf.fgh
)
[2] => array(
[0] => rtt#RERT.FDG
[1] => 4234235
[2] => 1
)
[3] => array(
[0] => WQEWQ#fgdg.h
)
)
I need some assistance because I already researched array_merge_recursive() and array_merge(), but I can't get the correct result.
If I need to use foreach() what must I do to merge these 3 arrays.
Wrote a little script:
$a = array
(
1=>"sadsad#fsdf.fgh",
2=>"rtt#RERT.FDG",
3=>"WQEWQ#fgdg.h",
);
$b = array
(
2 => 4234235
);
$c = array
(
2 => 1
);
$arrayKeys = array_unique(
array_merge(
array_keys($a),
array_keys($b),
array_keys($c)
)
);
$d = array_combine(
$arrayKeys,
array_fill(
0,
count($arrayKeys),
array()
)
);
foreach($a as $key => $value) {
if(!empty($a[$key])) {
$d[$key][] = $a[$key];
}
if(!empty($b[$key])) {
$d[$key][] = $b[$key];
}
if(!empty($c[$key])) {
$d[$key][] = $c[$key];
}
}
var_dump($d);
Also if you want to you can merge together the arrays using the variable names only
//names of the variables to merge together
$arrayVariableNames = array("a","b","c");
//merging array keys together
$arrayKeys = array();
foreach($arrayVariableNames as $variableName) {
$arrayKeys = array_merge(
$arrayKeys,
array_keys(${$variableName})
);
}
$arrayKeys = array_unique($arrayKeys);
//initialize the result array with empty arrays
$resultArray = array_combine(
$arrayKeys,
array_fill(
0,
count($arrayKeys),
array()
)
);
//loop through all the keys and add the elements from all the arrays
foreach($resultArray as $key => &$value) {
foreach($arrayVariableNames as $variableName) {
if(!empty(${$variableName}[$key])) {
$value[] = ${$variableName}[$key];
}
}
}
As you have no doubt discovered, array_merge_recursive() stubbornly smashes all numeric or "numeric string" keys into a 1-dimensional array. To avoid this behavior, you need to cast each of your arrays' initial keys as strings in a way that will not be assumed to be a number by array_merge_recursive().
Additionally you want to filter out all elements that have empty values.
I initially wrote a one-liner that performed the key re-casting then filtered the values, but it is less efficient that way. For your case, you should only use array_filter() on arrays that may possibly contain empty values.
Input Arrays:
$a=[1=>"sadsad#fsdf.fgh",2=>"rtt#RERT.FDG",3=>"WQEWQ#fgdg.h"];
$b=[1=>"",2=>"4234235",3=>""];
$c=[2=>1];
Code:
// remove empty values from all arrays that may have them
$b=array_filter($b,'strlen');
// for all arrays, cast numeric keys to string by prepending with a space
function addK($v){return " $v";}
$a=array_combine(array_map('addK',array_keys($a)),$a);
$b=array_combine(array_map('addK',array_keys($b)),$b);
$c=array_combine(array_map('addK',array_keys($c)),$c);
// merge arrays recursively
$merged=array_merge_recursive($a,$b,$c);
// cast keys back to numeric
$merged=array_combine(array_map('trim',array_keys($merged)),$merged);
// force all top-level elements to be arrays
foreach($merged as $k=>$v){
if(is_string($merged[$k])){$merged[$k]=[$v];}
}
var_export($merged);
Output:
array (
1 => array (
0 => 'sadsad#fsdf.fgh',
),
2 => array (
0 => 'rtt#RERT.FDG',
1 => '4234235',
2 => 1,
),
3 => array (
0 => 'WQEWQ#fgdg.h',
),
)
For readers who want to know the difference when array_merge_recursive() is run with no preparation:
array (
0 => 'sadsad#fsdf.fgh',
1 => 'rtt#RERT.FDG',
2 => 'WQEWQ#fgdg.h',
3 => '',
4 => '4234235',
5 => '',
6 => 1,
)
Notice the 1d array and the re-indexed keys? ...totally useless for the OP.
Finally, for anyone who wants to re-cast the keys to all arrays and would like to make my process more DRY, there may be an opportunity to set up a variadic function or similar. I merely didn't bother to pursue the notion because I didn't want to make my answer anymore complex and it is not a terrible amount of Repeating Myself.

Comparing Associative array and array

This is one array
Array ( [0] => 1 [1] => 2 )
The associative array is
Array ( [0] => Array ( [id_1] => 3 [id_2] => 1 ) [1] => Array ( [id_3] => 5 [id_4] => 3 ) )
I want to compare these arrays and get an array containing the values that are not present in the associative array
The result should be array(3) and array(5,3)
$array1 = array(1,2);
$array2 = array(
array(
'id_1' => 3,
'id_2' => 1
),
array(
'id_3' => 5,
'id_4' => 3,
)
);
I'm not sure if I understand the question, if you want to compare each array individually:
foreach($array2 as $subarray) {
var_dump(array_diff($subarray, $array1));
}
returns:
array
'id_1' => int 3
array
'id_3' => int 5
'id_4' => int 3
Otherwise if you don't want to loop through and flatten the array (using an array_flatten function from the php doc comments of array_values)
http://www.php.net/manual/en/function.array-values.php#97715
function array_flatten($a,$f=array()){
if(!$a||!is_array($a))return '';
foreach($a as $k=>$v){
if(is_array($v))$f=array_flatten($v,$f);
else $f[$k]=$v;
}
return $f;
}
var_dump(
array_unique(
array_diff(
array_flatten($array2), $array1
)
)
);
returns:
array
'id_1' => int 3
'id_3' => int 5
'id_4' is not shown because it doesn't have a unique value. You can remove the keys with array_values() or leave in 'id_4' by removing the array_unique() from the code.
something like this, maybe?
$array_a = array(1, 2);
$array_b = array(array(1, 3), array(3, 1));
$result = array();
foreach($array_b as $key => $sub_array_b){
foreach($sub_array_b as $sub_key => $value){
if(!in_array($value, $array_a) && !in_array($value, $result)) array_push($result, $value);
}
}
EDIT: I typed this before you edited your question. You can still modify the code above so that it creates a different array for each subarray in your associative array.

How to combine an array of keys with corresponding values from another array?

I have 2 arrays
Array ( [1] => Manufacturer [2] => Location [3] => Hours [4] => Model )
and
Array ( [Manufacturer] => John Deere [Location] => NSW [Hours] => 6320 )
I need to combine them and associate the values from the first array( Manufacturer, Location, hours , Model) as names in the 2nd array and if a specific values from the first array doesn't find associative name in the 2nd array to associate empty . For the example the result that I need from the above arrays is an array like this
Array ( [Manufacturer] => John Deere [Location] => NSW [Hours] => 6320 [Model] => )
If i use simple array_combine it says that PHP Warning: array_combine() [function.array-combine]: Both parameters should have equal number of elements
You can use a simple foreach loop:
$combined = array();
foreach ($keys as $key) {
$combined[$key] = isset($values[$key]) ? $values[$key] : null;
}
Where $keys is your first array with the keys and $values is your second array with the corresponding values. If there is no corresponding value in $values the value will be null.
Assuming $array1 and $array2 in order as you listed them, I think this would work:
$newArray = array();
while (list(,$data) = each($array1)) {
if (isset($array2[$data])) {
$newArray[$data] = $array2[$data];
} else {
$newArray[$data] = "";
}
}
Try array_merge(). This example appears to do what you want:
<?php
$keys = array( 1 => "Manufacturer", 2 => "Location", 3 => "Hours", 4 => "Model") ;
$canonical = array_combine(array_values($keys), array_fill(0, count($keys), null));
$data = array("Manufacturer" => "John Deere", "Location" => "NSW", "Hours" => 6320);
print_r(array_merge($canonical, $data));
If the array of keys is $array1, and the associative array with values is $array2:
$new_array = array_merge(array_fill_keys(array_flip($array1), ''), $array2));
This inverts your key array, filling it with '' values. Then when you merge the arrays, any duplicate keys will be overwritten by the second array, but unfilled keys will remain.

Categories