How to Organize Associative Array by Array Values in PHP

I have a set of values in an associative array that I need to sort based on another array of values.

For example:

If my associative array is: AssocArray = '122'=>'12', '123'=>'32', '232'=>'54', '343'=>'12'

I want to compare it with another array of values, orderArray = '232', '123'

If the value exists, move it to the top of AssocArray. So the final array should look like this.

AssocArray = '232'=>'54', '123'=>'32', '122'=>'12', '343'=>'12'

I don't have any code working right now as I'm still learning PHP.

Any help would be greatly appreciated :) Thank you.

Answer №1

Iterate over the elements in $orderArray, checking for existence of each key in $AssocArray. If found, add the element to a new array called $result and remove it from $AssocArray. Finally, merge any remaining items in $AssocArray with the contents of the $results array:


$AssocArray = array( '122'=>'12', '123'=>'32', '232'=>'54', '343'=>'12');
$orderArray = array('232', '123');

rsort($orderArray, SORT_STRING); // Sort order array in descending order

$result = array();
foreach($orderArray as $key) {
    if(isset($AssocArray[$key])) {
        $result[$key] = $AssocArray[$key];
        unset($AssocArray[$key]);
    }
}

foreach($AssocArray as $k => $v) {
    $result[$k] = $v;
}

print_r($result); // Output the resulting merged array

The output displayed is similar to what can be seen here:


Array
(
    [232] => 54
    [123] => 32
    [122] => 12
    [343] => 12
)

Answer №2

$items = array("apple", "banana");

function customOrder($item1, $item2){
    $item1Index = array_search($item1, $items);
    $item2Index = array_search($item2, $items);
    if($item1Index !== NULL && $item2Index != NULL){
        return $item1Index - $item2Index;
    }else if($item1Index === NULL){
        return 1;
    }else{
        return -1;
    }
}

uksort($list, "customOrder");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for authenticating Google AdMob's SSV using PHP?

I am facing an issue verifying ads to watch on mobile, but I can successfully verify them in the AdMob dashboard. error: error:0909006C:PEM routines:get_name:no start line $publicKey = openssl_get_publickey($result['keys'][0]['pem']); ...

Leverage PHP to retrieve information from a JSON file and integrate it into a dropdown menu on an HTML

I've been given a task to develop a PHP routine that will extract the ISO code and name from a geojson file for use in a dropdown list of countries on a website. This is completely new to me and I'm finding it difficult to understand the documen ...

Displaying outcomes from a pair of interlinked databases

I currently have two tables structured as: files id | path | filename changes id | file_id | change The file_id field is linked to the id in the files table. My use case for these tables involves storing information on which files have been changed a ...

I encountered no response when attempting to trigger an alert using jQuery within the CodeIgniter framework

Jquery/Javascript seem to be causing issues in codeigniter. Here is what I have done so far: In my config.php file, I made the following additions: $config['javascript_location'] = 'libraries/javascript/jquery.js'; $config['javas ...

Exploring ApacheBench tool for testing http requests in PHP

In my script, I am retrieving the value from a request using the following code: $body = file_get_contents('php://input'); I am currently testing this script with the ApacheBench (ab) utility. How can I send the value of php://input in ApacheBe ...

Using `href="#"` may not function as expected when it is generated by a PHP AJAX function

I am facing an issue with loading html content into a div after the page has loaded using an ajax call. The setup involves a php function fetching data from the database and echoing it as html code to be placed inside the specified div. Here is my current ...

Strategies for managing large data-sets and delivering a real-time user interface

As a developer working at an internet marketing firm focused on creating tools, I have specific requirements for the tools I build: The tools must be able to run in all web browsers. Users should either be able to upload a file (.csv) for processing or p ...

Discovering the Secrets of Laravel 5: Harnessing the Power of Vue.js to Access Data Attribute Values

I'm a beginner in vue js. Within our app, we have implemented validation to check if a value already exists in the database. I would like to enhance this feature by making it dynamic. To achieve this, I have added a data attribute to my field which is ...

Graph not displaying dates on the x-axis in flot chart

I've been attempting to plot the x-axis in a Flot chart with dates. I've tried configuring the x-axis and using JavaScript EPOCH, but have had no success so far. Here's a snippet of my code: <?php foreach($data[0] as $i => $d){ ...

How can you prevent external sources from accessing a script securely?

Alright, let's tackle this problem. Currently, I have a Facebook application that rewards users with points for filling out surveys. After completing a survey, a tracking pixel is activated to credit the user's account. The pixel executes a scri ...

What is the best way to create multiple PDF pages using mpdf1?

Currently using mpdf1 and looking to generate a PDF with a table of 4000 rows. Any suggestions on how to achieve this using mpdf1? Is there a method to speed up the process and avoid waiting for several minutes? ...

`Symfony2 API Key Authentication - Route not found for`

My approach to incorporating API key authentication was based on the guidelines provided in the documentation. This is how my code structure looks: src/Company/AuthBundle/Security/ApiKeyAuthenticator.php src/Company/AuthBundle/Security/ApiKeyUserProvider. ...

Unauthorized access: Soundcloud API error 401

I've been attempting to create a playlist using the SoundCloud API, but I keep encountering a 401 error when trying to set an access token. <?PHP require_once('Services/Soundcloud.php'); $client = new Services_Soundcloud('id ...

Tips for preserving checkbox state?

I am currently working on a web application project for a clinic and laboratory, specifically focusing on sending tests. I have implemented the code below to select the test category first, followed by the test name related to that category. However, when ...

Transforming the output from fetchAll() into a well-

Currently, I'm utilizing fetchAll(PDO::FETCH_ASSOC) to query my self-made database using an SQL statement. In order to visualize the retrieved data, I am employing print_r(). The values returned by print_r() look like this: Array ( [0] => Array ( ...

powershellUsing the cURL command with a PHP script

I am having trouble sending JSON data from the command line with curl to a php script and properly receiving it on the server-side. Here is what I have attempted so far: Running the following command in the command line: curl -H "Content-Type: applicati ...

Cloning dynamic drop downs causing them to malfunction

Currently, I have a table featuring just one row with two drop-down menus. The second drop-down's options are dependent on the selection made in the first drop-down via a JQuery change event. Following the table, there is a button that enables users t ...

How can PHP Ajax be used to determine when a modal should pop up?

Is there a way to automatically display a modal without refreshing the page? Currently, I have a button that submits to home.php and triggers the modal, but it requires a page refresh for the modal to appear. I'm looking for a solution that will eith ...

Is it safe to set content type as text/plain instead of application/json for JSON response?

I've been developing a PHP script to retrieve public JSON data, which will be accessed by JavaScript on the client side. However, I've encountered an issue with the server (LiteSpeed shared hosting) not having brotli/gzip compression enabled for ...

Using AJAX to dynamically update content via HTTP requests

Why do I keep seeing "loading..." instead of the content from data.php? xmlhttp = new XMLHttpRequest(); function fetchData () { xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState = 4 && xmlhttp.status == 20 ...