如何在php数组中合并单词

时间:2011-04-11 09:25:08

标签: php arrays

嗨我在以下列格式进行爆炸和其他操作后有一个数组。

[556] => Thorold
[557] => $130
[558] => Tilbury
[559] => $420
[560] => Tillsongbury
[561] => $225

[570] => Toronto
[571] => (Danforth
[572] => Area)
[573] => $55
[574] => Toronto
[575] => (Davisville
[576] => Area)
[577] => $50
[578] => Toronto
[579] => (Downtown
[580] => Area)
[581] => $50
[582] => Toronto
[583] => (East
[584] => York
[585] => Area)
[586] => $60

我想将单词索引中的单词和下一单词中的单词分组,即 $ data [0] =多伦多(市区) $ data [1] = $ 50.00

请建议或帮助。

4 个答案:

答案 0 :(得分:1)

<?
$source_array = array( 'A', 'B', '$50', 'C', 'D', 'E', '$200');
var_dump($source_array);

$portion = '';
$temp = array();
$result = array(array_pop($source_array));
while($item = array_pop($source_array)) {
   if(substr($item, 0, 1) == '$') {
     array_unshift($result, $item, implode($temp, ' '));
     $temp = array();
     $portion = '';
   } else {
     array_unshift($temp, $item);
   }
}

array_unshift($result, implode($temp, ' '));
var_dump($result);

答案 1 :(得分:1)

如果你的字符串是这样的(似乎是这样)

$str = "Toronto (Danforth Area) $55 Toronto (Davisville Area) $50";

并且城市名称(或其中的一部分)永远不会以数字结尾,您可以使用preg_split来获得所需的结构:

preg_split('/\s+(?=\$)|(?<=\d)\s+/', $str);

给出

Array
(
    [0] => Toronto (Danforth Area)
    [1] => $55
    [2] => Toronto (Davisville Area)
    [3] => $50
)

答案 2 :(得分:0)

这样的事情应该有效:

$newArray = array();
for ($i = 0, $max = count($oldArray); $i < $max; $i++) {
    $key = '';
    while (substr($oldArray[$i], 0, 1) <> '$') {
        $key .= ' ' . $oldArray[$i];
        $i++;
    }
    $newArray[trim($key)] = $oldArray[$i];
}

答案 3 :(得分:0)

我必须说我同意Felix的想法,如果这是我的项目,这可能是我将使用的方法(或类似的)。

但是,如果没有看到您正在执行的爆炸和其他操作来准备数据,我建议这样做:

代码:(Demo

$location='';
$result=[];
foreach($array as $v){
    if(substr($v,0,1)!='$'){
        $location.=($location?' ':'').$v;  // concatenate
    }else{
        array_push($result,$location,$v);  // store location then dollar amount
        // or make associative... $result[$location]=>$v;
        $location='';  // restart
    }
}
var_export($result);

输出:

array (
  0 => 'Thorold',
  1 => '$130',
  2 => 'Tilbury',
  3 => '$420',
  4 => 'Tillsongbury',
  5 => '$225',
  6 => 'Toronto (Danforth Area)',
  7 => '$55',
  8 => 'Toronto (Davisville Area)',
  9 => '$50',
  10 => 'Toronto (Downtown Area)',
  11 => '$50',
  12 => 'Toronto (East York Area)',
  13 => '$60',
)

这是我的正则表达式方法版本:(Demo

$string='Thorold $130 Tilbury $420 Tillsongbury $225 Toronto (Danforth Area) $55 Toronto (Davisville Area) $50 Toronto (Downtown Area) $50 Toronto (East York Area) $60';

var_export(preg_split('/ ?(\$\d+) ?/',$string,NULL,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY));
// same output as my above non-regex method

这使用更简单的模式并利用函数的标志来确保不会省略美元金额并且不会产生空元素。