将字符串转换为多维数组,然后按数组中的子值对其进行排序

时间:2009-08-31 17:45:35

标签: php arrays

我有一个这样的字符串:

事件名称|事件描述|事件类型|事件日期|事件时间|事件详细信息,
事件名称|事件描述|事件类型|事件日期|事件时间|事件详细信息,
事件名称|事件描述|事件类型|事件日期|事件时间|事件详细信息,
event name | event description | event type | event date | event time | event details,

这是一个字符串。我需要将其转换为数组,按事件日期重新排序,然后将其转换回字符串。

感谢任何帮助。非常感谢。

4 个答案:

答案 0 :(得分:2)

function sortStringByDate($str)
{
    $arr = explode(",\n", $str);
    foreach ($arr as $key => $val)
    {
        $arr[$key] = explode('|', $val);
    }
    $new_arr = array();
    foreach ($arr as $i => $vals)
    {
        $time = strtotime($vals[3].' '.$vals[4]);
        $new_arr[$time] = $vals;
    }
    ksort($new_arr);

    foreach ($new_arr as $key => $value)
    {
        $almost[] = implode('|', $value);
    }

    return implode(",\n", $almost);
}

答案 1 :(得分:1)

首先,您需要将字符串拆分为行,将其拆分为子数组,运行usort,然后将它们全部连接在一起。例如:

function lineSplit( &$item )
{
    $item = explode( '|', $item );
}

function lineSort( $item1, $item2 )
{
    return strcmp( $item1[ 3 ], $item2[ 3 ] );
}

function lineJoin( &$item )
{
    $item = join( '|', $item );
}

$str = '...';

// First split on the comma to get each line.
$lines = explode( ",\n", $str );

// Now split each line into subarrays
array_walk( $lines, 'lineSplit' );

// Perform the sort using a user-defined function.
usort( $lines, 'lineSort' );

// Now join the subarrays into strings.
array_walk( $lines, 'lineJoin' );

// And finally merge the lines again.
$str = join( ",\n", $lines );

答案 2 :(得分:0)

<?php
$string = "event name|event description|event type|2009-08-01|event time|event details,
event name|event description|event type|2009-08-02|event time|event details,
event name|event description|event type|2009-08-01|event time|event details,
event name|event description|event type|2009-08-03|event time|event details,";
   $arr = array();
   $strs = explode(',', $string);
   print_r($strs);
   foreach ($strs as $i => $str)
   {
      if (empty($str)) continue;

      $expl = explode('|', $str);
      $arr[strtotime($expl[3]) . $i] = $str;
   }
   ksort($arr);
   $result = implode(",\n", $arr);
   print_r($result);
?>

输出:

event name|event description|event type|2009-08-01|event time|event details,
event name|event description|event type|2009-08-01|event time|event details,
event name|event description|event type|2009-08-02|event time|event details,
event name|event description|event type|2009-08-03|event time|event details

答案 3 :(得分:0)

$arr = explode(',', $inputString);
$map = array()
foreach ($arr as $line){
    $lineArray = explode('|', $line);
    // convert date value to numerical representation of date+time
    $lineArray[3] = ...
    $map[] = $lineArray;
}

array_multisort($map[, ...]);

$result = array()
foreach($map as $lineArray){
    $result[] = implode('|', $lineArray);
}

// the resulting string:
implode(',', $result)