Home > Backend Development > PHP Tutorial > PHP数组排序的问题

PHP数组排序的问题

WBOY
Release: 2016-06-06 20:17:51
Original
1352 people have browsed it

有两个数组如下:

<code class="php">$aray1 = (
    'key3' => 'value3',
    'key2' => 'value2',
    'key1' => 'value1
);

$aray2 = ('key1', 'key3', 'key2');  //看清楚了,顺序不是123哦
</code>
Copy after login
Copy after login

请问php有没有内置的函数可以通过$array2将$array1排序成如下格式:

<code class="php">$aray1 = (
    'key1' => 'value1',
    'key3' => 'value3',
    'key2' => 'value2
);</code>
Copy after login
Copy after login

我看了下array_multisort()的文档,但是好像不支持。

回复内容:

有两个数组如下:

<code class="php">$aray1 = (
    'key3' => 'value3',
    'key2' => 'value2',
    'key1' => 'value1
);

$aray2 = ('key1', 'key3', 'key2');  //看清楚了,顺序不是123哦
</code>
Copy after login
Copy after login

请问php有没有内置的函数可以通过$array2将$array1排序成如下格式:

<code class="php">$aray1 = (
    'key1' => 'value1',
    'key3' => 'value3',
    'key2' => 'value2
);</code>
Copy after login
Copy after login

我看了下array_multisort()的文档,但是好像不支持。

貌似没有,array_multisort()主要是对多维数组排序

用用户自定义排序函数usort(),不过还是要自己写

<code>foreach($array2 as $i => $key) {
    $result[$key] = $array1[$key];
}
var_dump($result);</code>
Copy after login

<code class="php">$data = array();

array_walk($aray2,function($value, $key) use($aray1, &$data){
    $data[$value] = $aray1[$value];    
});

print_r($data);
</code>
Copy after login

根据我的经验,是没有这样的内部函数的

可以自己写一个方法

可以自己写一个方法

自己写一个呗

只有自己根据排序规则写一个了

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template