【问题标题】:displaying items in array ordered by id inside string在字符串中显示按 id 排序的数组中的项目
【发布时间】:2018-05-14 13:37:27
【问题描述】:

我想单独显示数组中的项目,按组排序。

项目存储在这样的字符串中:

$itemsString = "1:asd, 1:wer, 2:dfg, 3:gfg, 3:sdfss"; //and so forth

然后我像这样显示它们:

$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item){
 echo substr($item,2); //substr to get rid of the group id
}

编辑:解决方案

if(strpos($item, "1:")!==false){
echo substr($item,2);
}

【问题讨论】:

  • 你能解释一下当group id是'1:'时你打算对数据做哪些操作?
  • 我只想展示一下
  • 在第一个代码块中使用相同的 echo 行有什么问题?
  • 你是对的..我试过了,但不知何故我犯了一个错误,然后认为它无法完成..我知道为什么..它现在工作正常..谢谢提示

标签: php arrays sorting foreach


【解决方案1】:

您可以在冒号上对初始数组执行另一次分解,将数字和值分开,然后使用数字作为键将它们输入到数组中,例如:

$itemsString = "1:asd, 1:wer, 2:dfg, 3:gfg, 3:sdfss"; //and so forth

$sorted_array = [];
$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item) {
    $subItemsArray = explode(":", $item);
    $sorted_array[$subItemsArray[0]][] = $subItemsArray[1];
}

print_r($sorted_array);

这意味着 $sorted_array 会为您预先排序(或使用 ksort() 轻松排序):

Array
(
    [1] => Array
        (
            [0] => asd
            [1] => wer
        )

    [2] => Array
        (
            [0] => dfg
        )

    [3] => Array
        (
            [0] => gfg
            [1] => sdfss
        )

)

【讨论】:

    【解决方案2】:

    你可以这样显示它们

    $itemsArray = explode(", ", $itemsString);
    foreach($itemsArray as $item){
      if(strpos($item, "1:") || strpos($item, "1:") ===0 ){
        echo substr($item,2)
        ;}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 2016-09-08
      • 2014-10-28
      • 2014-04-23
      相关资源
      最近更新 更多