按特定的第三级子数组中的第一个元素对多维数组进行排序——先按其键排序,然后按其值排序



我需要按照多维数组子数组的第一个元素对多维数组的行进行排序。每一行可以在其attribute子阵列中具有动态命名的第一元素。我想先按第一个元素的键排序,然后按第一个元件的值排序。

我的输入数组如下:

$array = [
[
'tag' => 'meta',
'type' => 'complete',
'attributes' => ['property' => 'og:type', 'content' => 'website']
],
[
'tag' => 'meta',
'type' => 'complete',
'attributes' => ['name' => 'robots', 'content' => 'noindex, nofollow']
],
[
'tag' => 'meta',
'type' => 'complete',
'attributes' => ['name' => 'application', 'content' => 'My Application']
],
[
'tag' => 'meta',
'type' => 'complete',
'attributes' => ['http-equiv' => 'content-type', 'content' => 'text/html; charset=utf-8']
]
];

如何使用array_multisort()进行排序?

期望输出:

Array
(
[0] => Array
(
[tag] => meta
[type] => complete
[attributes] => Array
(
[http-equiv] => content-type
[content] => text/html; charset=utf-8
)
)
[1] => Array
(
[tag] => meta
[type] => complete
[attributes] => Array
(
[name] => application
[content] => My Application
)
)
[2] => Array
(
[tag] => meta
[type] => complete
[attributes] => Array
(
[name] => robots
[content] => noindex, nofollow
)
)
[3] => Array
(
[tag] => meta
[type] => complete
[attributes] => Array
(
[property] => og:type
[content] => website
)
)
)

我遇到了一些困难,因为第一列属性的键控不可预测。

带有自定义回调的usort看起来像:

usort($arr, function($a, $b) {
$aKeyFirst = array_key_first($a['attributes']);
// fallback, php version < 7.3
//$aKeyFirst = array_keys($a['attributes'])[0];

$bKeyFirst = array_key_first($b['attributes']);
// fallback, php version < 7.3
//$bKeyFirst = array_keys($b['attributes'])[0];

if ($aKeyFirst !== $bKeyFirst) {
return strcmp($aKeyFirst, $bKeyFirst);
} else {
return strcmp($a['attributes'][$aKeyFirst], $b['attributes'][$bKeyFirst]);
}
});

从属性键和值构建两个平面数组,然后使用array_multisort(),这将是最直接/最高效的——这不涉及迭代函数调用。

  • 第一CCD_ 6中的CCD_;数组破坏";并且允许您仅隔离循环主体中所需的数据
  • 嵌套的foreach()签名中的[]语法将键和值推入输出数组
  • break条件确保我们从不将每个属性子数组中的第一个元素推送到结果数组中

代码:(演示(

foreach ($array as ['attributes' => $attr]) {
foreach ($attr as $keys[] => $values[]) {
break;
}
}
array_multisort($keys, $values, $array);
var_export($array);

最新更新