Showing posts with label PHP array_merge. Show all posts
Showing posts with label PHP array_merge. Show all posts

Thursday, 30 August 2018

PHP merges two arrays on the same key value AND


I have two arrays. And I want to merge them on the same key AND value. If they have the same ur_user_id then they are merged. array2 only provides some additional data for array1, so the new_array.length = array1.length. array1 just gets the additional data from array2.


$array1 =
    array(
        array('ur_user_id'=> 1,'ur_fname'=>'PerA','ur_lname'=>'SonA'),
        array('ur_user_id'=> 2,'ur_fname'=>'PerB','ur_lname'=>'SonB'),
        array('ur_user_id'=> 3,'ur_fname'=>'PerC','ur_lname'=>'SonC'),
    );
$array2 =
    array(
        array('ur_user_id' => 5,'ur_code' => 'EE','ur_user_role' => 'testE'),
        array('ur_user_id' => 4,'ur_code' => 'DD','ur_user_role' => 'testD'),
        array('ur_user_id' => 6,'ur_code' => 'FF','ur_user_role' => 'testF'),
        array('ur_user_id' => 3,'ur_code' => 'CC','ur_user_role' => 'testC'),
        array('ur_user_id' => 1,'ur_code' => 'AA','ur_user_role' => 'testA'),
        array('ur_user_id' => 2,'ur_code' => 'BB','ur_user_role' => 'testB'),
    );

Then the new array must look like this. It will have both the values from the array1and array2.
$new_array =
    array(
        array('ur_user_id'=> 1,'ur_fname'=>'PerA','ur_lname'=>'SonA','ur_code' => 'AA','ur_user_role' => 'testA'),
        array('ur_user_id'=> 2,'ur_fname'=>'PerB','ur_lname'=>'SonB','ur_code' => 'BB','ur_user_role' => 'testB'),
        array('ur_user_id'=> 3,'ur_fname'=>'PerC','ur_lname'=>'SonC','ur_code' => 'CC','ur_user_role' => 'testC'),
    );

The array1.length is always less than or equal to array2.length never greater. And the order of both arrays will not be always ordered. I've tried the function below which I got somewhere here but it doesn't work for me and I'm not really good with loops.
function merge_common_keys(){
    $arr = func_get_args();
    $num = func_num_args();

    $keys = array();
    $i = 0;
    for ($i=0; $i<$num; ++$i){
        $keys = array_merge($keys, array_keys($arr[$i]));
    }
    $keys = array_unique($keys);

    $merged = array();

    foreach ($keys as $key){
        $merged[$key] = array();
        for($i=0; $i<$num; ++$i){
            $merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
        }
    }
    return $merged;
}

Based on the given arrays the result is like this. It only merges on the same key.
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [ur_user_id] => 1
                    [ur_fname] => PerA
                    [ur_lname] => SonA
                )

            [1] => Array
                (
                    [ur_user_id] => 5
                    [ur_code] => AA-BB-CC
                    [ur_user_role] => testE
                )

        )


Try out this code, It might help you, it's short and without traversing loops:
    usort($array2,function($a,$b){
        return strnatcmp($a['ur_user_id'],$b['ur_user_id']);
    });
    $array3 = array_replace_recursive($array1, $array2);

    $result = array_uintersect($array3,$array1,function($a,$b){
        return strnatcmp($a['ur_user_id'],$b['ur_user_id']);
    });
    print_r($result);

Output
Array
(
    [0] => Array
        (
            [ur_user_id] => 1
            [ur_fname] => PerA
            [ur_lname] => SonA
            [ur_code] => AA
            [ur_user_role] => testA
        )

    [1] => Array
        (
            [ur_user_id] => 2
            [ur_fname] => PerB
            [ur_lname] => SonB
            [ur_code] => BB
            [ur_user_role] => testB
        )

    [2] => Array
        (
            [ur_user_id] => 3
            [ur_fname] => PerC
            [ur_lname] => SonC
            [ur_code] => CC
            [ur_user_role] => testC
        )

)


PHP: Sort set based on another table


 I have visited similar question here but not getting what i want in php. Suppose i have 2 arrays. All checking should be case insensitive. say Field0 is same as field0 or fiEld1 is same as Field1.


array1 is array(
"0"=>"field0",
"1"=>"field1",
"2"=>"field2",
"3"=>"field3",
);

array2 is array(
"0"=>"field3",
"1"=>"field2",
"2"=>"field0",
"3"=>"field1",
"4"=>"field6",
"5"=>"field5",
);

Now I want array2 to be sorted based on array1 like the following:
array2 is array(
"0"=>"field0",
"1"=>"field1",
"2"=>"field2",
"3"=>"field3",
"4"=>"field6",
"5"=>"field5",
);

look here array1 has 4 elements so array2 should be sorted based exactly 4 elements of array1 and rest 2 element (index 4,5 of array2) should as it is in array2 before.

Try array_intersect combined with array_diff:
<?php
$array1 = array(
    "0"=>"field0",
    "1"=>"field1",
    "2"=>"field2",
    "3"=>"field3",
);

$array2 = array(
    "0"=>"field3",
    "1"=>"field2",
    "2"=>"field0",
    "3"=>"field1",
    "4"=>"field6",
    "5"=>"field5",
);

$array3 = array_merge(
    array_intersect($array1, $array2),
    array_diff($array2, $array1)
);

var_dump($array3);

Update
For a case insensitive approach, use array_map to guarantee all entries in both arrays are lower-cased:
$array3 = array_map('strtolower', $array1);
$array4 = array_map('strtolower', $array2);

$array5 = array_merge(
    array_intersect($array3, $array4),
    array_diff($array4, $array3)
);

var_dump($array5);

PHP sort array comparing the value and pushing the smaller values ​​last


I have a value and comparing that value i want to change order of an array


for eg. here 3 is value so i need array order to be
5,6,1,2
so values less then 3 shifts last in array.
<?php

$value=3;

$array=array(6,2,5,1);

asort($array);

print_r($array);

?>


Please have a look on the below code, it may help you. You need to use array_filter with call back function to make 2 arrays then u can merge them.
  $value=3;
  $array=array(6,2,5,1);
  asort($array);
  $right = array_filter($array, function($elem) use($value){
      return $elem < $value;
  });
  $left = array_filter($array, function($elem) use($value){
     return $elem > $value;
  });
  //print_r($right);
  //print_r($left);
  $res = array_merge($left,$right);
  print_r($res);

Monday, 6 July 2015

PHP: Add duplicate elements to an array

<?php
$columnsArr = array('','');
$colArr = array(2=>'DIABETES WITH ACUTE COMPLICATIONS'
,5=>'DIABETES WITH CHRONIC COMPLICATIONS'
,8=>'DIABETES'
,11=>'MALNUTRITION'
,14=>'OBESITY'
,17=>'RHEUMATOID'
,20=>'DRUG/ALCOHOL'
,23=>'PSYCH'
,26=>'NEURO'
,29=>'CARDIAC DISEASE'
,32=>'VASCULAR DISEASE'
,35=>'LUNG DISEASE'
,38=>'KIDNEY DISEASES');
foreach($colArr as $key=>$val){
  $columnsArr1 = array_fill($key,3, $val);
 $columnsArr = array_merge($columnsArr,$columnsArr1); 
}
echo "<pre>";
  print_r($columnsArr);
echo "</pre>";

?>

Friday, 26 June 2015

PHP: Use of Default Arguments in PHP

Use of default arguments is very common and helpful in programming. Default arguments provide a useful way for the smooth and correct execution of algorithms in the logic. I am going to share a professional usage of "php default argument array" in the codes.

I really love this method as it helps me a lot for merging user and default arguments in the different codes. You can say, it is one of Must Have Method, for every developer.

Let’s write a method "chip_print" which will print our output. I use this function regularly in my classes to get a quick print of string, variables and arrays.

Function chip_print

function chip_print( $var ) {
    echo "<pre>";
    print_r($var);
    echo "</pre>";
}

Function chip_parse_args

Now i am going to write the main method which will merge default arguments with user arguments.
function chip_parse_args( $args = array() ) {

    $defaults = array (
        'arg1'  =>   'default',
        'arg2'  =>   'default'
    );

    $result = array_merge( $defaults, $args );

    return $result;

}

You have noticed that i have used built-in function of PHP, array_merge.

Usage Example 1

You can use this function without passing any argument.

$result = chip_parse_args();
chip_print($result);

Output

Array
(
    [arg1] => default
    [arg2] => default
)

You have noticed that function has returned default values as we have passed not input to the method.

Usage Example 2

We will pass one argument to the method.
   
$args = array (
    'arg1'  =>   'modified1'
);
$result = chip_parse_args($args);
chip_print($result);

Output
   
Array
(
    [arg1] => modified1
    [arg2] => default
)

You have noticed that function has replaced argument 1 with the passed value.

Usage Example 3

We will pass two arguments as a test to the method.
   
$args = array (
    'arg1'  =>   'modified1',
    'arg2'  =>   'modified2'
);
$result = chip_parse_args($args);
chip_print($result);

Output

   
Array
(
    [arg1] => modified1
    [arg2] => modified2
)

You have noticed that function has replaced both arguments with the passed values.

Complete Tutorial

   
<?php

/*
|--------------
| Chip Print
|--------------
*/

function chip_print( $var ) {

    echo "<pre>";
    print_r($var);
    echo "</pre>";

}

/*
|--------------
| Chip Parse Arguments
|--------------
*/

function chip_parse_args( $args = array() ) {

    $defaults = array (
        'arg1'  =>   'default',
        'arg2'  =>   'default'
    );

    $result = array_merge( $defaults, $args );

    return $result;

}

/*
|--------------
| Example 1
|--------------
*/

$result = chip_parse_args();
chip_print($result);

/*
|--------------
| Example 2
|--------------
*/

$args = array (
    'arg1'  =>   'modified1'
);
$result = chip_parse_args($args);
chip_print($result);

/*
|--------------
| Example 3
|--------------
*/

$args = array (
    'arg1'  =>   'modified1',
    'arg2'  =>   'modified2'
);
$result = chip_parse_args($args);
chip_print($result);

?>

Wednesday, 1 October 2014

PHP add missing keys between arrays

I have the following code:

$a = array('a' => 'some value', 'b' => 'some value', 'c' => 'some value');
$b = array('a' => 'another value', 'd' => 'another value', 'e' => 'another value', 'f' => 'another value');
$c = array('b' => 'some more value', 'x' => 'some more value', 'y' => 'some more value', 'z' => 'some more value');

$d = array($a, $b, $c);
Printing $d will output:

Array
(
    [0] => Array
        (
            [a] => some value
            [b] => some value
            [c] => some value
        )

    [1] => Array
        (
            [a] => another value
            [d] => another value
            [e] => another value
            [f] => another value
        )

    [2] => Array
        (
            [b] => some more value
            [x] => some more value
            [y] => some more value
            [z] => some more value
        )

)
How would I go about combining the array keys and end up with the following output?

Array
(
    [0] => Array
        (
            [a] => some value
            [b] => some value
            [c] => some value
            [d] =>
            [e] =>
            [f] =>
            [x] =>
            [y] =>
            [z] =>
        )

    [1] => Array
        (
            [a] => another value
            [b] =>
            [c] =>
            [d] => another value
            [e] => another value
            [f] => another value
            [x] =>
            [y] =>
            [z] =>
        )

    [2] => Array
        (
            [a] =>
            [b] => some more value
            [c] =>
            [d] =>
            [e] =>
            [f] =>
            [x] => some more value
            [y] => some more value
            [z] => some more value
        )

)


Answer1:
Yes you can use array_merge in this case:

$a = array('a' => 'some value', 'b' => 'some value', 'c' => 'some value');
$b = array('a' => 'another value', 'd' => 'another value', 'e' => 'another value', 'f' => 'another value');
$c = array('b' => 'some more value', 'x' => 'some more value', 'y' => 'some more value', 'z' => 'some more value');
$d = array($a, $b, $c);
$keys = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($d)) as $key => $val) $keys[$key] = '';
$data = array();
foreach($d as $values) {
    $data[] = array_merge($keys, $values);
}

echo '<pre>';
print_r($data);

Answer2:

$a = array('a' => 'some value', 'b' => 'some value', 'c' => 'some value');
$b = array('a' => 'another value', 'd' => 'another value', 'e' => 'another value', 'f' => 'another value');
$c = array('b' => 'some more value', 'x' => 'some more value', 'y' => 'some more value', 'z' => 'some more value');

$d = array_merge(array_merge($a, $b),$c);

foreach($d as $k=>$v){
    $aN[$k] = isset($a[$k])?$a[$k]:'';
    $bN[$k] = isset($b[$k])?$b[$k]:'';
    $cN[$k] = isset($c[$k])?$c[$k]:'';
}
$dN = array($aN, $bN, $cN );

Wednesday, 24 September 2014

array_merge in PHP

array_merge() function is used to merge two or more arrays.

Syntax:  array_merge(array1,array2,array3...)

Parameters Description:
array1 : Required. Specifies an array.
array2 : Optional. Specifies an array.
array3 : Optional. Specifies an array.

Tip : You can assign one array to the function, or as many as you like.
Note : If you assign one array to the array_merge() function, and the keys are integers, the function returns a new array with integer keys starting at 0.

Example:

<?php
$daysarr1 = array( "a"=>"Sunday","b"=>"Monday" );
$daysarr2 = array( "c"=>"Tuesday","b"=>"Thursday");
print_r( array_merge($daysarr1,$daysarr2) );
$daysarr3 = array( 3=>"Monday",4=>"Sunday" );
echo "<br />"."using only one parameter";
print_r( array_merge($daysarr3) );
?>

O/P:


Array ( 
          [a] => Monday
          [b] => Thursday
          [c] => Tuesday
         )
using only one parameter
Array (
            [0] => Monday
            [1] => Sunday
         )