Compare keys in arrays and make new array with comparison values - php

I have 2 arrays that I need to compare and then create a new array with the key staying the same, but adding a new array of as value with the two values from the two arrays.
$array1 = (['SE'] => (string) '123', ['DE'] => (string) '456', ['DK'] => (string) '678');
$array2 = (['SE'] => (string) '999', ['DE'] => (string) '888', ['US'] => (string) '777');
So what I want to achieve is to get the value from both arrays where the key is equal to one another.
I then need to echo it in a similar fashion;
echo '<table>';
foreach($newCompparedArray as $k => $v){
echo '<tr>';
echo '<td>'.$k.'</td><td>'.$v->value1.'</td><td>'.$v->value2.'</td>';
echo '</tr>';
}
echo '</table>';
Another thing is I need the key to only get the values if the key was present in the initial array (i.e. if a key isn't in array1 but is present in array2, don't add this key or it's values to the new array).

This should give you what you want:
$array1 = array('SE' => '123', 'DE' => '456', 'DK' => '678');
$array2 = array('SE' => '999', 'DE' => '888', 'US' => '777');
$keysInBothArrays = array_intersect(array_keys($array1),array_keys($array2));
$newCompparedArray = array();
foreach ($keysInBothArrays as $key) {
$newCompparedArray[$key] = array($array1[$key],$array2[$key]);
}
// print_r($newCompparedArray); exit;
echo '<table>';
foreach($newCompparedArray as $k => $v){
echo '<tr>';
echo '<td>'.$k.'</td><td>'.$v[0].'</td><td>'.$v[1].'</td>';
echo '</tr>';
}
echo '</table>';
The trick is to get the keys which are in both arrays first.

Assuming I understood the output you wanted as
Array(
[SE] => Array ( [0] => 123, [1] => 999 )
[DE] => Array ( [0] => 456, [1] => 888 )
[DK] => Array ( [0] => 678 )
[US] => Array ( [0] => 777 )
)
I would use this code
$array1 =array ('SE' => '123', 'DE' => '456', 'DK' => '678');
$array2 =array ('SE' => '999', 'DE' => '888', 'US' => '777');
$t =array ();
foreach ( $array1 as $key => $value )
$t [$key] =array ($value);
foreach ( $array2 as $key => $value ) {
if ( !isset ($t [$key]) )
$t [$key] =array ($value);
else
$t [$key] [] =$value;
}
//print_r ($t);
foreach ( $t as $key => $value ) {
echo '<tr>';
echo "<td>$key</td><td>" . implode ("</td><td>", $value) . '</td>';
echo "</tr>\n";
}

Loop the first array, check for the value in the second array and if it exists add both:
foreach($array1 as $k => $v) {
$newCompparedArray[$k] = isset($array2[$k]) ? array($v, $array2[$k]) : $v;
}
Then your display loop would be:
foreach($newCompparedArray as $k => $v) {
echo '<td>'.$k.'</td><td>'.$v[0].'</td><td>'.$v[1].'</td>';
}
Obviously in the first loop if you define array('value1'=>$v, 'value2'=>$array2[$k]) then you could use $v['value1] and $v['value2'].
The shorter version:
$newCompparedArray = array_intersect_key(array_merge_recursive($array1, $array2), $array1);

Related

transfer specific index of array to a new array - php

I want to delete an index from array and insert it into in new array. I want two things which i tried to explain one is
Array
(
[index1] => Deleted
[index4] => Inserted
)
Array
(
[index3] => test
[index4] => Inserted
)
Array
(
[index2] => numbers
[index3] => test
[index4] => Inserted
)
Array
(
[index1] => Deleted
)
now i want if arraysize is 1
foreach($array as $arrays){
array_push($array1,($arrays[0]));
unset ($arrays[0]);
}
i want to remove
Array
(
[index1] => Deleted
)
from $array and $array to be
[index1] => Deleted
second is if $array is
Array
(
[index2_123] => numbers
[index3_level] => test
[index4_test] => Inserted
)
i want a new array with $array1 as
Array
(
[index3_level] => test
)
and $array1 is modified to
Array
(
[index2_123] => numbers
[index4_test] => Inserted
)
Try this way,
$arr = Array
(
'index1' => 'Deleted',
'index2' => 'numbers',
'index3' => 'test',
'index4' => 'Inserted'
);
$arr1 = $arr2 = array();
$i = 0;
foreach($arr as $key => $value){
if($i%2 == 0){
$arr1[$key] = $value;
}else{
$arr2[$key] = $value;
}
$i++;
}
Output
$arr1
Array
(
[index1] => Deleted
[index3] => test
)
$arr2
Array
(
[index2] => numbers
[index4] => Inserted
)
And if you don't need that value then you can use it as
$i = 0;
foreach($arr as $key => $value){
if($i%2 == 0){
$arr[$key] = $value;
}else{
unset($arr[$key]);
}
$i++;
}
print_r($arr);
Output:
Array
(
[index1] => Deleted
[index3] => test
)
Loop through them and generate the array -
$new = array();
foreach($yourarray as $key => $val) {
$index = str_replace('index', '', $key); // get the key index
if($index % 2 != 0) { // check for odd or even
$new[$key] = $val; // set the new array
unset($yourarray[$key]); // delete from the main array
}
}
Update
For any index use a counter
$i = 0;
$new = array();
foreach($yourarray as $key => $val) {
if($i % 2 != 0) { // check for odd or even
$new[$key] = $val; // set the new array
unset($yourarray[$key]); // delete from the main array
}
$i++;
}
You can use a combination of array_flip and array_diff_key to filter the first array, then use array_diff filter the second:
$specificIndex = array('index1', 'index3');
$array1 = array_diff_key($array, array_flip($specificIndex));
$array2 = array_diff($array, $array1);
Demo.
If you want get in an array only certain elements of your choice you can do something like:
$specificIndex = array('index1', 'index3');
$selectedItem = array_intersect_key($array, array_flip($specificIndex));
Demo.
<?php
$array = array(
'index1' => 'Deleted',
'index2' => 'numbers',
'index3' => 'test',
'index4' => 'Inserted',
);
$specificIndex = 'index3';
$array1=array();
foreach($array as $key => $value){
if($key==$specificIndex){
$array1[$key] = $value;
unset($array[$specificIndex]);
}
}
print_r($array);
print_r($array1);
http://3v4l.org/TvZ19

How to replace array keys with another array values

I have two arrays and I want to replace the second array keys with the first array values if both keys matches.
As an example: Replace A with Code And B with name
How to do this;
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
foreach($replacement_keys as $key => $value){
foreach($value as $sk => $sv){
foreach($array as $rk => $rv){
if($sk == $rk ){
$sk = $rv;
}
}
}
}
echo "<pre>";
print_r($value);
echo "</pre>";
exit;
I want the result to be like this
array(
[0] => Array
(
[name] => ahmed
[code] => 1020
)
[1] => Array
(
[name] => sara
[code] => 2020
)
)
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
foreach($replacement_keys as &$value)
{
foreach ($array as $key => $name) {
$value[$name] = $value[$key];
unset($value[$key]);
}
}
var_dump($replacement_keys);
Try this:
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
$newArray = array();
foreach($replacement_keys as $key => $value)
{
foreach($value as $key2 => $value2)
{
if(isset($array[$key2]))
{
$newArray[$key][$array[$key2]] = $value2;
}
else
{
$newArray[$key][$key2] = $value2;
}
}
}
print_R($newArray);
This should work for you, nice and simple (I'm going to assume that A should be name and B should be code):
(Here I go through each array from $replacement_keys with array_map() and replace the array_keys() with the array_values() of $array. Then I simply get all array values from $replacement_keys and finally I array_combine() the replaced array keys with the corresponding array values)
$result = array_map("array_combine",
array_map(function($v)use($array){
return str_replace(array_keys($array), array_values($array), array_keys($v));
}, $replacement_keys),
$replacement_keys
);
output:
Array ( [0] => Array ( [code] => sara [name] => 2020 ) [1] => Array ( [code] => ahmed [name] => 1010 ) )
array_fill_keys
(PHP 5 >= 5.2.0, PHP 7)
array_fill_keys — Fill an array with values, specifying keys
Description
array array_fill_keys ( array $keys , mixed $value )
Fills an array with the value of the value parameter, using the values of the keys array as keys.
http://php.net/manual/en/function.array-fill-keys.php

Foreach Value in Array Check to see if that value is Greater than any value in another Array

I have two arrays which the key is a [part id]. The value is record => Qty:Length. I want to be able to check if any of the values under the same part id from the sencond array is greater than the length of the first array. For example the Part id 2099 in the second array has a qty:length of 14:11.25 and that is greater than the 6:3.33 which I want that to return true in PHP. I Have a function to split up the qty and length but after that I am unsure where to go. It returns "Warning: explode() expects parameter 2 to be string," Any Help Appreciated.
Array
(
[2099] => Array
(
[360] => 6:3.33
[362] => 14:8.75
)
[2130] => Array
(
[361] => 4:2.5
)
)
Array
(
[2099] => Array
(
[360] => 12:8.33
[362] => 14:11.25
)
[2130] => Array
(
[361] => 24:3.5
)
)
My PHP:
foreach ($a as $partid=>$qty_length){
$ex_part = explode(":", $qty_length);
}
You can do a nested foreach loop to find the difference
<?php
$array1 = array(2099 => array(360 => "6:3.33",362 => "14:8.75"),2130 => array(361 => "4:2.5"));
$array2 = array(2099 => array(360 => "12:8.33",362 => "14:11.25"),2130 => array(361 => "24:3.5"));
foreach($array1 as $key => $value)
{
foreach ($value as $key1 => $value1) {
// $array1[$key][$key1] get the value of array one curreny key
// $array2[$key][$key1] get the value of array two current key
$one = explode(':',$array1[$key][$key1]); // array one value e.g 360 => "6:3.33"
$two = explode(':',$array2[$key][$key1]); // array two value e.g 360 => "12:8.33"
// do what ever you want here
if($one[0] > $two[0])
{
echo "array one key " . $key1 . " is bigger <br>";
}else{
echo "array two key " . $key1 . " is bigger <br>";
}
}
}
$arr =Array
(
'2099' => Array
(
'360' => '6:3.33',
'362' => '14:8.75'
),
'2130' => Array
(
'361' => '4:2.5'
),
'2131' => Array
(
'362' => '24:3.5'
)
);
$arr1=Array
(
'2099' => Array
(
'360' => '12:8.33',
'362' => '14:11.25'
),
'2130' => Array
(
'361' => '24:3.5'
),
'2131' => Array
(
'362' => '20:3.5'
)
);
foreach ($arr as $partid=>$qty_length){
foreach($qty_length as $key=>$val){
$ex_part = explode(":", $val);
// print_r($ex_part);
$ex_part1 = $arr1[$partid];
$len = sizeof($ex_part1);
foreach( $ex_part1 as $key1=>$val1){
$ex_part1 = explode(":", $arr1[$partid][$key1]);
if($ex_part[0] < $ex_part1[0] && $ex_part[1] < $ex_part1[1]){
$len--;
if($len == 0){
echo $ex_part1[0]."<br>";
}else{
continue;
}
}else if($ex_part[0] >= $ex_part1[0] && $ex_part[1] >= $ex_part1[1]){
$len--;
if($len == 0){
echo $ex_part[0]."else <br>";
}else{
continue;
}
}
}
}
}
you can add more conditions also.

How to combine two multidimensional arrays with showing duplicate keys or if duplicate, must add the values

I got main array keys a1 and a2.
$array1 = array(a1=>array(200,300,300), a2=>array(100,600,200));
$array2 = array(a1=>array('gen','gen2','gen'), a2=>array('gen2','gen3','gen3'));
I want my output to be
'a1'=>array(
'gen'=>200
'gen2'=>300
'gen'=>300
),
'a2'=>array(
'gen2'=>100
'gen3' =>600
'gen3' =>200
)
or
'a1'=>array(
'gen'=>500
'gen2'=>300
)
'a2'=>array(
'gen2'=>100
'gen3'=>800
)
I have tried this code but not enough, It doesn''t show the duplicate or it's better if it shows the sum of of the value ofduplicate keys
<?php
$array1 = array(a1=>array(200,300,300), a2=>array(100,600,200));
$array2 = array(a1=>array('gen','gen2','gen'), a2=>array('gen2','gen3','gen3'));
$result = array();
foreach($array1 as $k => $v) {
$result[$k] = array_combine($array2[$k], $v);
}
print_r($result);
?>
Thanks you very much for your help
$array1 = array(
'a1' => array(200,300,300),
'a2' => array(100,600,200));
$array2 = array(
'a1' => array('gen','gen2','gen'),
'a2' => array('gen2','gen3','gen3'));
$result = array('a1' => array(), 'a2' => array());
foreach($array2 as $k => $v) {
foreach ($v as $k2 => $v2){
if (array_key_exists($v2, $result[$k])){
$result[$k][$v2] += $array1[$k][$k2];
} else {
$result[$k][$v2] = $array1[$k][$k2];
}
}
}
Output:
Array
(
[a1] => Array
(
[gen] => 500
[gen2] => 300
)
[a2] => Array
(
[gen2] => 100
[gen3] => 800
)
)

changing keys of a multidimensional array

I have a multidimensional array as shown below. How do I change the keys that start with "id of"?
Array
(
[0] => Array
(
[id of ten] => 1871
[name] => bob
)
[1] => Array
(
[id of nine hundred thousand] => 12581
[name] => barney
)
)
Normally, you'd do something like:
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['old'];
unset($array[$k]['old']);
}
In my case, the key changes dynamically (there are thousands of keys in my multidimensional array and they are random but they will always start w/ "id of...")
thx!
I'm wondering if this is what you are looking for:
<?php
$array = array(
array(
"id of one" => 434,
"name" => "bob"
),
array(
"id of two" => 9323,
"name" => "ted"
)
);
$c_array = count($array);
for ($i = 0; $i < $c_array; $i++)
{
foreach ($array[$i] as $key => $value)
{
if (substr($key, 0, 5) == 'id of') {
$array[$i][substr($key, 6)] = $value;
unset($array[$i][$key]);
}
}
}
print_r($array);
?>
NOTE: Includes use of substr() instead of strpos(). See Gumbo's comment below.
https://ideone.com/xBV5L
This outputs:
Array
(
[0] => Array
(
[name] => bob
[one] => 434
)
[1] => Array
(
[name] => ted
[two] => 9323
)
)
This solution is very clean. Array_shift, does two things at once: returns first element (which has the id), and deletes it from the array, so you can directly assign it to the $new_array at 'id'
$new_arr=array();
foreach ( $array as $arr)
{
$new_arr[array_shift($arr)] = $arr;
}
If the 'id of' key is always the first element of the array, you can use the following:
foreach ($input as &$value)
{
$value['key'] = reset($value);
$key = key($value);
unset($value[$key]);
}
Otherwise, the following worked for me:
foreach ($input as &$value)
{
foreach ($value as $key=>$el) {
if (substr($key, 0, 5) == 'id of') {
$value['key'] = $el;
unset($value[$key]);
}
}
}
In both cases you can change $value['key'] to whatever you want the new key to be.

Categories