Home  >  Article  >  Backend Development  >  How to convert php array to index array

How to convert php array to index array

PHPz
PHPzOriginal
2023-04-26 14:19:13495browse

In PHP programming, array is a very important data type, which facilitates us to store, process and operate data. Among them, the index array is one of the most commonly used array types. It uses a number as the key name, corresponding to a numerical value or a string value. Here, we will discuss how to perform permutations on indexed arrays.

1. Array sorting method

In PHP, we can use the sort() function to sort the index array in ascending order, and the rsort() function to sort the index array in descending order, as shown below:

//升序排列 
$numbers = array(3, 1, 5, 2, 4); 
sort($numbers); 
print_r($numbers); 

//降序排列 
$numbers = array(3, 1, 5, 2, 4);  
rsort($numbers);  
print_r($numbers);

The output results are:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) 
Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )

2. Array transposition method

Array transposition refers to exchanging rows and columns in a multi-dimensional array to generate a new array . For example, for a two-dimensional array:

$nums = array( 
    array(1, 2, 3), 
    array(4, 5, 6), 
    array(7, 8, 9) 
);

We can use the array_map() function and the null value to transpose it, as follows:

function transposeArray($array, $nullFiltered = true) { 
    $aOut = array_map(null, ...$array); 
    return ($nullFiltered) ? array_filter($aOut) : $aOut; 
} 
 
print_r(transposeArray($nums));

The output result is:

Array ( 
    [0] => Array ( [0] => 1 [1] => 4 [2] => 7 ) 
    [1] => Array ( [0] => 2 [1] => 5 [2] => 8 ) 
    [2] => Array ( [0] => 3 [1] => 6 [2] => 9 ) 
)

Here, we first define a function called transposeArray, passing in an array and a Boolean variable. Among them, we use the variable length parameter (...$array) introduced in PHP 5.6 version to implement the null value for each sub-array in the multi-dimensional array to be transposed. Finally, we use the array_filter() function to filter out the null values ​​​​in the result array and get the required results.

3. Combination of array sorting and transposition

In the actual programming process, we often need to sort a multi-dimensional array according to a certain keyword, and after sorting, we also need to The array is transposed. For example, we have the following associative array with numbers as keys:

$arr = array(
    3 => array("name" => "apple", "price" => 2.5),
    1 => array("name" => "banana", "price" => 1.5),
    4 => array("name" => "orange", "price" => 3.5),
    2 => array("name" => "pear", "price" => 2.0)
);

Next, we can define the sortArray() function to sort the array in ascending order according to 'price' and transpose the result array, In this process, you can also pass in a field name to sort by different fields. The code is as follows:

function sortArray($arr, $keyName = '', $sortOrder = 'ASC') {
    $sortResult = array();
    $arrLen = count($arr);
    if ($arrLen > 0) {
        $priceArr = array();
        for ($i = 0; $i < $arrLen; $i++) {
            if ($keyName != '' && isset($arr[$i][$keyName])) {
                $priceArr[] = $arr[$i][$keyName];
            } else {
                $priceArr[] = $arr[$i]['price'];
            }
        }
        if (strtolower($sortOrder) == 'desc') {
            array_multisort($priceArr, SORT_DESC, SORT_NUMERIC, $arr);
        } else {
            array_multisort($priceArr, SORT_ASC, SORT_NUMERIC, $arr);
        }
        $sortResult = transposeArray($arr);
    }
    return $sortResult;
}

print_r(sortArray($arr, 'price', 'ASC'));

When we pass in 'price' as the second parameter, the output result is:

Array ( 
    [name] => Array ( [0] => banana [1] => pear [2] => apple [3] => orange ) 
    [price] => Array ( [0] => 1.5 [1] => 2 [2] => 2.5 [3] => 3.5 ) 
)

Here, we first determine whether the incoming array is empty. If not, first get the price value in the original array, and use the array_multisort() function to sort the array in ascending or descending order. Then, we use the transposeArray() function to transpose the resulting array.

Summary

To sum up, this article introduces the method of sorting index arrays in PHP. Sorting is implemented through the sort() and rsort() functions, transpose of the array is implemented using the transposeArray() function, and sorting and transposition of multi-dimensional arrays are implemented by combining sorting and transposing. Mastering these methods will bring greater convenience and flexibility to our PHP programming and improve our program development efficiency.

The above is the detailed content of How to convert php array to index array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn