排序一系列变量

时间:2017-10-26 16:48:19

标签: php sorting variables

如何对此进行排序,来自:

$res_events = "|2,20171021|1,20171007|2,20171007|1,20171028|2,20171014|1,20171014|2,20171028|1,20171021|";

为:

$res_events = "|1,20171007|1,20171014|1,20171021|1,20171028|2,20171007|2,20171014|2,20171021|2,20171028|";

2 个答案:

答案 0 :(得分:1)

爆炸和排序数组。
然后将其内爆回到字符串。

$res_events = "|2,20171021|1,20171007|2,20171007|1,20171028|2,20171014|1,20171014|2,20171028|1,20171021|";
$arr = explode("|", $res_events);

Sort($arr);
// Remove one of the two empty values in array
Unset($arr[0]);
// Implode and add last "|"
$new =implode("|", $arr)."|"; 

输出:

|1,20171007|1,20171014|1,20171021|1,20171028|2,20171007|2,20171014|2,20171021|2,20171028

https://3v4l.org/DIYYX

答案 1 :(得分:1)

看看这是否有效......

<?php // demo/temp_vincent.php
/**
 * https://stackoverflow.com/questions/46959713/sort-a-series-of-vars
 */
ini_set('display_errors', TRUE);
error_reporting(E_ALL);

echo '<pre>';

// TEST DATA AND DESIRED RESULTS
$res_events = "|2,20171021|1,20171007|2,20171007|1,20171028|2,20171014|1,20171014|2,20171028|1,20171021|";
$chk_events = "|1,20171007|1,20171014|1,20171021|1,20171028|2,20171007|2,20171014|2,20171021|2,20171028|";

// TRIM OFF UNNECESSARY DELIMITERS
$res_events = trim($res_events, '|');

// MAKE AN ARRAY SO WE CAN SORT
$arr = explode('|', $res_events);
sort($arr);

// RECONSTRUCT THE STRING
$new_events = '|' . implode('|', $arr) . '|';

// TEST FOR SUCCESS
if ($new_events == $chk_events) echo 'Success!';