I need your help in PHP I have 2 array. $old array have 5000 records example:
$old = Array ( 'branch' => Array ( '1' => Array ( 'slug' => 'script', 'version' => '1.0.0', 'link' => 'oldfile' ), '2' => Array ( 'slug' => 'pos', 'version' => '2.4.0', 'link' => 'oldfile' ), '3' => Array ( 'slug' => 'stock', 'version' => '5.0.0', 'link' => 'oldfile' ), '4' => Array ( 'slug' => 'sale', 'version' => '22.0.2', 'link' => 'oldfile' ), ) );
New Array not much maybe 10-30 records
$new = Array ( 'branch' => Array ( '1' => Array ( 'slug' => 'script', 'version' => '1.23.0', 'link' => 'newfile' ), '2' => Array ( 'slug' => 'stock', 'version' => '5.9.0', 'link' => 'newfile' ), ) );
I want to compare version from old array with new array and want to update data in old array by change to new version and link Example new array have new version available and new download link.
I need function that get this result
$old = Array ( 'branch' => Array ( '1' => Array ( 'slug' => 'script', 'version' => '1.23.0', 'link' => 'newfile' ), '2' => Array ( 'slug' => 'pos', 'version' => '2.4.0', 'link' => 'oldfile' ), '3' => Array ( 'slug' => 'stock', 'version' => '5.9.0', 'link' => 'newfile' ), '4' => Array ( 'slug' => 'sale', 'version' => '22.0.2', 'link' => 'oldfile' ), ) );
i’m using
$result = array_replace_recursive($old, $new);
but it will replace all to old file
Advertisement
Answer
A simple array_replace could have solved the issue if you kept a consistent indexing when you create a new array
So my solution here finds common slug between the old and new, then remove them from the old before replacing.The assumption is that the ‘slug’ keys are always present and labelled the same also new array cannot be empty.Hence no checking present.
foreach($new['branch'] as $arrwithin){ //get arrays within the new multidim array foreach($old['branch'] as $key => $value){ if($value['slug'] == $arrwithin['slug']){ //check if the same slugs in new array are present in the old array $del[] = $key; //Get index of the old arrays within multidim where similar slugs are found as a new array } } } $oldclean = array_diff_key($old['branch'], array_flip($del)); //Remove the arrays which contain old slugs that have been updated in new array $final['branch'] = array_merge($new['branch'],$oldclean); //Merge old cleaned up array with new array since well unwanted slugs are already removed echo "<pre>"; print_r($final); //New multidim array with updated arrays echo "</pre>";
Works on PHP 5.1 and above(Tested on PHP 8)