【问题标题】:how to split string into an array and sort them如何将字符串拆分为数组并对它们进行排序
【发布时间】:2019-09-20 06:58:54
【问题描述】:

我正在开发一个模块,我将字符串存储在以逗号(,)分隔的列中,并且我已将字符串拆分为一个数组并将该数组添加到下拉列表中,但是当我对多个列执行此操作时,它没有在下拉列表中对数组进行排序

这里是代码

   $pp=DB::table('gcp_projects')->where('niche','!=',' ')->where('niche','!=','')->where('niche','!=',null)->orderBy('niche')->pluck('niche');
$testing=explode(",",$pp);


$arr=array();
$tttt=array();
for($i=0;$i<=count($pp);$i++)
{
 $arr= explode(",",$pp);
 $temp = preg_replace("/[^a-zA-Z 0-9]+/", "", $arr);
$tttt=array_unique($temp);
sort($tttt);

}

【问题讨论】:

  • 您正在循环遍历数组$pp,但在循环中您仍在使用$pp。你需要使用$pp[$i] 让它在正确的物品上爆炸。
  • $tttt 将始终具有 for 循环的最后一次迭代的值,我认为这不是您想要的。你想达到什么目的?
  • where('niche','!=',null) 您不会以这种方式检查NULL。使用whereNotNull()。另外,这个问题的意义何在?你在排序什么?您的输入和预期输出?
  • 感谢您的反馈,我已经存储了多个利基(每列 3 个利基),我必须将这些利基分开并在下拉列表中对其进行排序,但它显示一半已排序,一半未排序

标签: php arrays laravel


【解决方案1】:
<?php 

// Use preg_split() function 
$string = "123,456,78,000"; 
$str_arr = preg_split ("/\,/", $string); 
print_r($str_arr); 

// use of explode 
$string = "123,46,78,000"; 
$str_arr = explode (",", $string); 
print_r($str_arr); 
?> 

你可以这样做并使用类似的排序选项

$values = array ("zercggj.co.uk", "lkjhg.org.au", "qqxze.org.au",
                 "bfhgj.co.uk", "sdfgh.org.uk");

echo "<br>input:<br>";
foreach ($values as $host) echo "$host<br>";

// create a suitable structure
foreach ($values as $host)
{
    $split = explode('.', $host, 2);
    $printable[$split[1]][] = $split[0];
}

// sort by domains
asort ($printable);

// output
echo "<br>sorted:<br>";
foreach ($printable as $domain => $hosts)
{
    echo "domain: $domain<br>";

    // sort hosts within the current domain
    asort ($hosts);

    // display them
    foreach ($hosts as $host)
        echo "--- $host<br>";
}

【讨论】:

    【解决方案2】:

    到目前为止,我找到了适合我的解决方案

    $pp=DB::table('gcp_projects')->whereNotNull('niche')->orderBy('niche')->pluck('niche')->toArray();
    
    
    $aa=implode(',',$pp);
    
    $myArray = explode(',', $aa);
    $im=implode(' ',$myArray);
    $ex=explode(' ',$im);
    $tttt=array_unique($ex);
     sort($tttt);
     $str = preg_replace("/[^a-zA-Z 0-9]+/", "", $tttt);
      $result = array_filter($str); 
    

    【讨论】:

      【解决方案3】:

      你必须提到orderby ASC OR DESC

      orderBy('created_at', 'asc')orderBy('created_at', 'asc')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-28
        • 2016-11-21
        • 1970-01-01
        • 2017-12-02
        • 1970-01-01
        • 2017-06-13
        • 1970-01-01
        • 2013-03-06
        相关资源
        最近更新 更多