在php中对数组值进行分组

时间:2012-06-26 17:20:29

标签: php

我有一个类似

的数组值
$array[0]="Test|121";
$array[1]="Test|goo";
$array[2]="Test|example";

我需要将其更改为

$array[0]="Test";
$array[1]="121";
$array[2]="goo";
$array[3]="example";

任何人都可以告诉我该怎么做。

2 个答案:

答案 0 :(得分:1)

$array[0]="Test|121";
$array[1]="Test|goo";
$array[2]="Test|example";

$result = explode( '|', array_shift( $array));
foreach( $array as $k => $v) {
    $parts = explode( '|', $v);
    $result[] = array_pop( $parts);
}

var_dump( $result);

这会产生错综复杂的 output

array(4) {
  [0]=>
  string(4) "Test"
  [1]=>
  string(3) "121"
  [2]=>
  string(3) "goo"
  [3]=>
  string(7) "example"
}

答案 1 :(得分:0)

function cutStr(&$elem, $key)
{
    $ret = explode('|', $elem);

    if ( $key == 0 )
        $elem = $ret[0];
    else
        $elem = $ret[1];
}

$array[0]="Test|121";
$array[1]="Test|goo";
$array[2]="Test|example";

array_walk($array, 'cutStr');
print_r($array);

试试这个。

相关问题