【问题标题】:Split na array to a multidimensional array alphabetically按字母顺序将 na 数组拆分为多维数组
【发布时间】:2017-11-13 05:40:51
【问题描述】:

我收到了一个 PHP 数组,格式如下:

[0] => Array
        (
            [mainCatID] => 2
            [mainCatCode] => cat2
            [mainCatDesc] => Acupuncture
            [mainCatAddedDate] => 2016-10-12 10:22:49
            [mainCatStatus] => active
        )

[1] => Array
    (
        [mainCatID] => 3
        [mainCatCode] => cat3
        [mainCatDesc] => Medical
        [mainCatAddedDate] => 2016-10-12 10:22:49
        [mainCatStatus] => active
    )

[2] => Array
    (
        [mainCatID] => 4
        [mainCatCode] => cat4
        [mainCatDesc] => Aids & Hiv
        [mainCatAddedDate] => 2016-10-12 10:22:49
        [mainCatStatus] => active
    )


[3] => Array
    (
        [mainCatID] => 1
        [mainCatCode] => cat1
        [mainCatDesc] => Brains
        [mainCatAddedDate] => 2016-10-12 10:22:49
        [mainCatStatus] => active
    )

我想要实现的是根据 [mainCatDesc] 第一个字母将数组拆分为不同的字母“块”。所以预计结果如下:

一个

针灸 艾滋病和艾滋病毒

B

大脑

M

医疗

提前感谢您的帮助!干杯!

  • 已编辑 *

目前我只有

$con = open_connection();
$allMainCatArray = getAllMainCat($con);
close_connection($con);

echo "<pre>";
print_r($allMainCatArray);
echo "</pre>";

【问题讨论】:

  • 你需要提供代码,你试过什么?
  • 啊啊码的意思?
  • 这段代码是什么?这段代码和你的问题有什么关系?
  • 到目前为止,我只有一个 print_r() 来输出我返回的数组。我尝试使用数组块,但函数需要的参数似乎不适合我的需要
  • 你试过简单的循环吗?还有一些数组推送?

标签: php arrays multidimensional-array split alphabetical


【解决方案1】:

做这个简单的循环:

$newArray = [];//create a new array
foreach($array as $item) {
   $letter = $item['mainCatDesc'][0];//get the first letter


   if (!ctype_alpha($letter)) {//test if its letter
     $newArray['#'][] = $item['mainCatDesc'];

   } else if(count($newArray[$letter])) {//test if the letter is in the array
      $newArray[$letter][] = $item['mainCatDesc'];//save the value
   } else {
       $newArray[$letter] = [$item['mainCatDesc']];
   }
}

【讨论】:

  • 嗨,代码不能正常工作,但我设法对其进行了微调以使其正常工作!感谢您的帮助!
  • 我想,但是问是否可以添加一个条件,为不以字母开头的项目创建一个新数组?意思是说如果它以数字或符号开头,它会在#标签下创建一个新数组,而不是A B C
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多