如何按特定列值的前导整数对子数组进行排序?

发布于 2024-11-05 14:27:30 字数 886 浏览 7 评论 0原文

下面的数组应按 cat_url_title 的第一个数字按升序排序。

Array
(
    [0] => Array
        (
            [cat_id] => 14
            [parent_id] => 2
            [cat_url_title] => 20-a-43m
        )

    [1] => Array
        (
            [cat_id] => 13
            [parent_id] => 2
            [cat_url_title] => 16-a-20m            
        )

    [2] => Array
        (
            [cat_id] => 12
            [parent_id] => 2
            cat_url_title] => 12-a-16m
        )
)

//get the first number
foreach( $arr as $k => $v )
{
    $segs = explode("-",$v['cat_url_title']);
    $nbr = $segs[0]; //this will be 20, 16 or 12
} 

cat_url_title 值以 12 开头的子数组应变为 $arr[0]16 应保留为 < code>$arr[1] 和 20 应移至 $arr[2]

我怎样才能实现这个目标?

The array below should be sorted by the first number of cat_url_title in an ascending direction.

Array
(
    [0] => Array
        (
            [cat_id] => 14
            [parent_id] => 2
            [cat_url_title] => 20-a-43m
        )

    [1] => Array
        (
            [cat_id] => 13
            [parent_id] => 2
            [cat_url_title] => 16-a-20m            
        )

    [2] => Array
        (
            [cat_id] => 12
            [parent_id] => 2
            cat_url_title] => 12-a-16m
        )
)

//get the first number
foreach( $arr as $k => $v )
{
    $segs = explode("-",$v['cat_url_title']);
    $nbr = $segs[0]; //this will be 20, 16 or 12
} 

The subarray with the cat_url_title value starting with 12 should become $arr[0], 16 should remain as $arr[1], and 20 should move to $arr[2].

How can I achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

疯狂的代价 2024-11-12 14:27:30

你的方法很好,在获得第一个数字后,创建一个新数组,其中包含数字作为键,数组的内容作为值:

$newArray = array();
foreach($arr as $k => $v)
{
  $segs = explode("-", $v['cat_url_title']);
  $newArray[ $segs[0] ] = $v;
}
ksort($newArray);
print_r($newArray);

这应该可以工作。

you're on a good way, after getting the first numbers create a new array containing the number as a key and the contents of the array as value:

$newArray = array();
foreach($arr as $k => $v)
{
  $segs = explode("-", $v['cat_url_title']);
  $newArray[ $segs[0] ] = $v;
}
ksort($newArray);
print_r($newArray);

that should work.

旧瑾黎汐 2024-11-12 14:27:30

请参阅 usort() PHP 函数。

关于 php 中数组排序函数的有趣页面: http://us.php.net/手册/en/array.sorting.php

See the usort() php function.

Interesting page about array sorting functions in php: http://us.php.net/manual/en/array.sorting.php

野味少女 2024-11-12 14:27:30

单行:

array_multisort(array_map('end', $array), SORT_NUMERIC, $array);

假设:

$array = array (
    0 => array (
        'cat_id' => 14,
        'parent_id' => 2,
        'cat_url_title' => '20-a-43m'
    ),
    1 => array (
        'cat_id' => 13,
        'parent_id' => 2,
        'cat_url_title' => '16-a-20m'
    ),
    2 => array (
        'cat_id' => 12,
        'parent_id' => 2,
        'cat_url_title' => '12-a-16m'
    )
);

One-liner:

array_multisort(array_map('end', $array), SORT_NUMERIC, $array);

Assuming:

$array = array (
    0 => array (
        'cat_id' => 14,
        'parent_id' => 2,
        'cat_url_title' => '20-a-43m'
    ),
    1 => array (
        'cat_id' => 13,
        'parent_id' => 2,
        'cat_url_title' => '16-a-20m'
    ),
    2 => array (
        'cat_id' => 12,
        'parent_id' => 2,
        'cat_url_title' => '12-a-16m'
    )
);
提赋 2024-11-12 14:27:30

这是我用来对数组进行排序的函数:

function array_sort($array, $on, $order='SORT_DESC' /*or SORT_ASC*/ )
    {
      $new_array = array();
      $sortable_array = array();

      if (count($array) > 0) {
          foreach ($array as $k => $v) {
              if (is_array($v)) {
                  foreach ($v as $k2 => $v2) {
                      if ($k2 == $on) {
                          $sortable_array[$k] = $v2;
                      }
                  }
              } else {
                  $sortable_array[$k] = $v;
              }
          }

          switch($order)
          {
              case 'SORT_ASC':   
                  asort($sortable_array);
              break;
              case 'SORT_DESC':
                  arsort($sortable_array);
              break;
          }

          foreach($sortable_array as $k => $v) {
              $new_array[] = $array[$k];
          }
      }
      return $new_array;
    } 

用法:

array_sort($restaurants_top, "score", 'SORT_DESC');

$restaurants_top = 餐馆列表
“score” = 数组键
SORT_DESC = 排序方向

Here is a function I use to sort arrays:

function array_sort($array, $on, $order='SORT_DESC' /*or SORT_ASC*/ )
    {
      $new_array = array();
      $sortable_array = array();

      if (count($array) > 0) {
          foreach ($array as $k => $v) {
              if (is_array($v)) {
                  foreach ($v as $k2 => $v2) {
                      if ($k2 == $on) {
                          $sortable_array[$k] = $v2;
                      }
                  }
              } else {
                  $sortable_array[$k] = $v;
              }
          }

          switch($order)
          {
              case 'SORT_ASC':   
                  asort($sortable_array);
              break;
              case 'SORT_DESC':
                  arsort($sortable_array);
              break;
          }

          foreach($sortable_array as $k => $v) {
              $new_array[] = $array[$k];
          }
      }
      return $new_array;
    } 

Usage:

array_sort($restaurants_top, "score", 'SORT_DESC');

$restaurants_top = a list of restaurants
"score" = an array key
SORT_DESC = direction of sorting

酒儿 2024-11-12 14:27:30

Tomasz 对 array_multisort() 的建议是一个聪明的、声明性的、简洁的技术已在 php 版本中使用多年。如果此任务在我的项目中,我可能会使用 array_multisort()。

我可能建议,为了项目稳定性(如果数据结构被扩展/更改),显式命名要排序的列。以下代码片段还避免了迭代 end() 调用。

array_multisort(array_column($array, 'cat_url_title'), SORT_NUMERIC, $array);

作为学术练习,我将展示一些现代替代方案。

从 PHP7 开始,spaceship 运算符还提供了简洁的语法。要隔离第一个连字符之前的数字子字符串,请将字符串转换为整数。

usort($array, function($a, $b) {
    return (int)$a['cat_url_title'] <=> (int)$b['cat_url_title'];
});

从 PHP7.4 开始,箭头函数语法 生成 usort() 调用更简洁,但如果您不习惯语法,则可能更难以阅读。

usort($array, fn($a, $b) => (int)$a['cat_url_title'] <=> (int)$b['cat_url_title']);

与我几乎所有的 php 帖子一样,这里是在线演示,以证明我的所有代码片段均按预期运行。

应避免此页面上多次迭代输入数组的片段。


ps 如果您希望对四个数字/字母子字符串上的 cat_url_title 值进行排序,您可以将这些子字符串作为数组写入 spaceship 运算符的每一侧,它将从左到右评估子字符串以确定排序结果。

代码:(演示)

usort($array, function($a, $b) {
    return (preg_match_all('~[a-z]+|\d+~', $a['cat_url_title'], $out) ? $out[0] : ['','','',''])
           <=> 
           (preg_match_all('~[a-z]+|\d+~', $b['cat_url_title'], $out) ? $out[0] : ['','','','']);
});

pps 这可能是 version_compare() 的一个很好的例子。不幸的是,它对于我的测试电池中的琴弦来说并不可靠。记下此演示16-a-20n子数组的最终位置。我相信该函数忽略了最后一个字母,因为 16-a-20m16-a-20n 之间的评估为 0

至于具有一致的 am 子字符串位置的示例字符串,它可以完美地进行自然排序。

代码:(演示)

usort($array, function($a, $b) {
    return version_compare($a['cat_url_title'], $b['cat_url_title']);
});

Tomasz's suggestion of array_multisort() is a clever, declarative, and concise technique that has been available in php versions for many years. I'd likely use array_multisort() if this task was in my project.

I might suggest, for project stability (in case the data structure is extended/changed), to explicitly name the column to be sorted by. The following snippet also avoids making iterated end() calls.

array_multisort(array_column($array, 'cat_url_title'), SORT_NUMERIC, $array);

I'll show a couple of modern alternatives as an academic exercise.

From PHP7, the spaceship operator also provides a concise syntax. To isolate the numeric substring before the first hyphen cast the strings as integers.

usort($array, function($a, $b) {
    return (int)$a['cat_url_title'] <=> (int)$b['cat_url_title'];
});

From PHP7.4, arrow function syntax makes a usort() call more concise, but arguably more cryptic to read if you are not used to the syntax.

usort($array, fn($a, $b) => (int)$a['cat_url_title'] <=> (int)$b['cat_url_title']);

As with nearly all of my php posts, here is an online demo to prove that all of my snippets function as intended.

Snippets on this page that iterate the input array multiple times should be avoided.


p.s. if you wish to sort the cat_url_title values on the four numeric/alphabetic substrings, you can write these substrings as arrays on each side of the spaceship operator and it will evaluate the substrings from left to right to determine the sorting outcomes.

Code: (Demo)

usort($array, function($a, $b) {
    return (preg_match_all('~[a-z]+|\d+~', $a['cat_url_title'], $out) ? $out[0] : ['','','',''])
           <=> 
           (preg_match_all('~[a-z]+|\d+~', $b['cat_url_title'], $out) ? $out[0] : ['','','','']);
});

p.p.s. This is may a good case for version_compare(). Unfortunately, it is not reliable for the strings in my test battery. Take note of the final position of the 16-a-20n subarray in this demo. I believe that the function is ignoring the final letter because the evaluation is 0 between 16-a-20m and 16-a-20n.

As for your sample strings with consistent a and m substring positions, it works perfectly to naturally sort.

Code: (Demo)

usort($array, function($a, $b) {
    return version_compare($a['cat_url_title'], $b['cat_url_title']);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文