PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 20, 2022

[FIXED] Sort an array of numbers by another predefined, non-exhaustive array of number, then sort ascending

 January 20, 2022     lookup, php, sorting     No comments   

Issue

Given two arrays $A1 and $A2, sort $A1 in such a way that the relative order among the elements will be same as those in $A2. For the elements not present in $A2, move them to the back of the array in ascending order.

$A1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8];
$A2 = [2, 1, 8, 3];

Desired output:

[2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9]

Coding attempt:

$sorted = array();

foreach($a1 as $key => $value) {
    if(in_array($value, $a2)) {
        $sorted[array_search($value, $a1)] = $value;
    }
}

Solution

This can be done via for each loop :

$arr1 = array(2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8); // array to be sorted
$arr2 = array(2, 1, 8, 3); // refrence array for sort logic
// Output: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}

$sortarr = array(); // array to store final sorted values
foreach ($arr2 as $a) {
    foreach ($arr1 as $k => $b) {
        if($b==$a) {
            $sortarr[]=$b;
            unset($arr1[$k]);
        }
    }

}

$finalarr = array_merge($sortarr, $arr1);

print_r($finalarr);


Answered By - Sitepose
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing