简体   繁体   中英

How to replace array keys with predefined values

Assuming that I have following situation:

I have an array like this:

$array = array(1 => "text1",2 => "text2", 3 => "Text3" , 4 => "Text4");

After some functions I receive a string which contains these values:

$string = "2,1,4,3"; // this values are dynamic 

What I want to achieve is to sort that array ( $array ) in the string's order; so the result should be:

<--- some function --- > 
$result = array(2 => "text2",1=> "text1",4=>"Text4",3=>"Text3"));

PHP's array_multisort() function - http://php.net/manual/en/function.array-multisort.php

Untested, but probably something like:

array_multisort(explode(",", $string), $array);

Keys may get lost though.

$keyArr = explode(',', $string);
$sortedArr = array();

foreach ($keyArr as $key)
{
    $sortedArr[$key] = $array[$key];
}
  1. Break up the string into indexes with explode
  2. Make an empty array $result
  3. Iterate over the exploded array of keys, doing $result[$key] = $input[$key]

See it in action .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM