logo
down
shadow

PHP - Merge and Combine Array


PHP - Merge and Combine Array

By : user3042473
Date : November 28 2020, 12:01 PM
around this issue If your willing to make the product_id the key, then you can do it like this:
code :
$a = [
  0 => [
    "product_id" => "a",
    "quantity_1" => "1"
  ],
  1 => [
    "product_id" => "b",
    "quantity_1" => "2"
  ],
  2 => [
    "product_id" => "c",
    "quantity_1" => "1"
  ]
];

$b =  [
  0 => [
    "product_id" => "a",
    "quantity_2" => "1"
  ],
  1 => [
    "product_id" => "d",
    "quantity_2" => "2"
  ]
];

 print_r(
      array_replace_recursive(
             array_column($a, null, 'product_id'),
             array_column($b, null, 'product_id')
      )
 );
Array
(
    [a] => Array
        (
            [product_id] => a
            [quantity_1] => 1
            [quantity_2] => 1
        )

    [b] => Array
        (
            [product_id] => b
            [quantity_1] => 2
        )

    [c] => Array
        (
            [product_id] => c
            [quantity_1] => 1
        )

    [d] => Array
        (
            [product_id] => d
            [quantity_2] => 2
        )

)
 print_r(
    array_values(
      array_replace_recursive(
             array_column($a, null, 'product_id'),
             array_column($b, null, 'product_id')
      )
    )
 );
$c = [];

foreach(array_merge($a,$b) as $v){
    $k = $v['product_id'];
    if(!isset($c[$k])){
        $c[$k] = $v;
    }else{
        $c[$k] = array_merge($c[$k],$v);
    }
}

print_r($c);


Share : facebook icon twitter icon
php array merge & combine

php array merge & combine


By : PattiMN
Date : March 29 2020, 07:55 AM
I hope this helps you . I have three arrays & i like to convert it in one multidimensional array. , Use this:
code :
  $array1=array('Kathy', 'Adam', 'Jenny');
  $array2=array('student','teacher','driver');
  $array3=array(2, 5, 8);
  $mix=array();

  for($i=0;$i<count($array1);$i++){
         $mix[$i]=array('name'=>$array1[$i],'profession'=>$array2[$i],'SL'=>$array3[$i]);
   }

  print_r($mix);
php array combine/merge

php array combine/merge


By : David Toledo
Date : March 29 2020, 07:55 AM
should help you out hi to all stackoverflow members, please help me with my problem regarding array manipulation. , Try this:
code :
$new_array = array();
foreach($stores_array as $t) {
    $new_array[$t] = $items_array;
    $new_array[$t]["store"]=$t;
}

echo '<pre>';
print_r($new_array);  
echo '<pre/>';
Php three array merge combine

Php three array merge combine


By : user4715806
Date : March 29 2020, 07:55 AM
Any of those help , You can try this:
code :
$arr1 = array(1,2,3); 
$arr2 = array("a","b","c"); 
$arr3 = array("1a","2b","3c");

$i = 0;
foreach ($arr1 as $key => $value) {
    $newArr[] = $value.",".$arr2[$i].",".$arr3[$i];
$i++;
}
echo implode("<br/>", $newArr);
1,a,1a
2,b,2b
3,c,3c
merge duplicate objects in an array and combine sub array of each object

merge duplicate objects in an array and combine sub array of each object


By : user3142997
Date : March 29 2020, 07:55 AM
it fixes the issue I am trying to merge objects based off of Id, and merge each array that lives inside each account (object), but instead of merging the contents of accountList, the code overwrites the array, if there is a matching id. , I think, reduce() would do the job:
code :
const accounts = [{"Id":103,"accountList":[{}]},{"Id":103,"accountList":[{"tokenId":"5aasdasdsdnjn3434nadd","featureId":2840}]},{"Id":112,"accountList":[{"tokenId":"5d30775bef4a722c38aefaaa","featureId":2877}]},{"Id":112,"accountList":[{"tokenId":"5d30775bef4a722c38aefccc","featureId":2856}]}];

const res = accounts.reduce((r,{Id,accountList}) => {
  const matchIdx = r.findIndex(item => item.Id == Id);
  return matchIdx < 0 ? 
    [...r,{Id, accountList: accountList.filter(obj => Object.values(obj).length != 0)}] :
    (r[matchIdx].accountList.push(...accountList), r);
}, []);

console.log(res);
.as-console-wrapper {min-height: 100%}
Merge or combine an array like this? on PHP

Merge or combine an array like this? on PHP


By : user3786875
Date : March 29 2020, 07:55 AM
Hope this helps You can "promote" the second level elements to first level elements via call_user_func_array(). And while array_merge() re-indexes the array, array_replace() does not but retains the original keys which makes this a one-liner:
Related Posts Related Posts :
  • How to search a row that has been joined with another table
  • How to do mysql LEFT JOIN for Google multiple line chart (php, mysql)?
  • Find the two longest strings separated by dash in PHP
  • Cannot access private property with Set method in Symfony
  • How to compare 2 array of PHP objects then fill in empty string if data not match?
  • strtotime gives back false result to strings in an array
  • How to create Url that contain name and id laravel
  • Codeigniter: Models not working with an error: Undefined property: CI_Loader
  • How to use + or - operators as parameters in Doctrine prepared SQL statement?
  • PHP unpack overlfow variable memory limit
  • How to check the URL's structure using PHP preg_match?
  • PHP preg_replace - text will not be recognized
  • Show image from other domain without showing the domain name - PHP
  • How to run and watch local server at the same time?
  • Access form request from Observer laravel
  • single quote problem with preg_replace_callback
  • How to Create A Unique URL for each product enquiry form for Google Analytics Tracking
  • Laravel email configuration: what am I missing?
  • Assign indexed array values to multidimensional array?
  • Custom WordPress stylesheet not loading
  • Data attribute only returning first value
  • How to list all roles with Permissions,in spatie permission Package?
  • How to achieve this number pattern with n input
  • How to iterate array inside array data in laravel ,output are given below
  • To get output of movie with its genre
  • Extracting some data from a JS object literal string in PHP using Regex
  • axios and vuex are deleting wrong index in array
  • Setting empty CURLOPT_POSTFIELDS
  • Laravel 5.8 use subdomain as API endpoint beside domain.com/api
  • Error while add data in database SQL Server 2016
  • Does PhpStorm allow to skip PHPDoc tags when type hints is declared?
  • html classes are changed to Attributes
  • Using json to import multidimensional data
  • passing data from the view to the controller, where the data comes from another controller
  • How to extract integer and decimal numbers in PHP string correctly?
  • Parsing Sub-Object from an XML Feed with objects
  • Getting error "Unknown column 'text' in 'field list'"
  • How to properly get onedrive access token via php and curl
  • How to add spell check to a php function
  • Is it posible to create css rules with php?
  • Pretty URL with $_GET method
  • Wordpress always load same page - index.php
  • Find value in array and return with new from different array
  • PHP multiple file upload with different keys
  • Can't modify times one a time without weird errors
  • Get size of scraped image with domcrawler (Goutte)
  • Laravel - Ordering a collection of models
  • PHP Fatal error: Uncaught Error: Call to a member function setFetchMode() on boolean
  • Strict Standards: Only variables should be passed by reference in /main_dir/sub_dir/backup.php
  • Uncaught Google_Exception: (update) unknown parameter: 'copyRequiresWriterPermission'
  • Laravel 5 form does not redirect with old input
  • How to get values greater than or equal to in Mysql database sql when its a value like 1:00 PM?
  • PHP datediff overday issue
  • Masking an auto incrementing primary key
  • How to grab a String BEFORE a certain word
  • ZF2 Routing Multiple Controllers based on route constraints
  • How to deregister/dequeue jquery.sticky.js in Elementor (Pro)?
  • How to fix errors counting words in text plain with PHP?
  • How to get View data in Laravel in custom helper or directive
  • Creating a new data entry into a database with eloquent and trying to access the variable in the url
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org