-1

我需要通过匹配索引值从序列化数组中获取值。我的未序列化数组值就像

          Array ( [info1] => test service [price_total1] => 10 
          [info2] => test servicing [price_total2] => 5 )

我需要像这样显示数组

       Array ( [service_1] => Array ([info]=>test service [price_total] => 10 ) 
            [service_2] => Array ([info]=>test servicing [price_total] => 5 ))

买我得到如下结果

              Array ( [service_1] => Array ( [price_total] => 10 ) 
                [service_2] => Array ( [price_total] => 5 ) )

我的编码是

   public function getServices($serviceinfo) {
    $n = 1;
    $m = 1;
    $matches = array();
    $services = array();
    print_r($serviceinfo);
    if ($serviceinfo) {
        foreach ($serviceinfo as $key => $value) {
            if (preg_match('/info(\d+)$/', $key, $matches)) {
            print_r($match);
                $artkey = 'service_' . $n;
                $services[$artkey] = array();
                $services[$artkey]['info'] = $serviceinfo['info' . $matches[1]];
                $n++;
            }
             if ($value > 0 && preg_match('/price_total(\d+)$/', $key, $matches)) {
             print_r($matches);
                $artkey = 'service_' . $m;
                $services[$artkey] = array();
                $services[$artkey]['price_total'] = $serviceinfo['price_total' . $matches[1]];
                $m++;
            }
        }
    }
    if (empty($services)) {
        $services['service_1'] = array();
        $services['service_1']['info'] = '';
        $services['service_1']['price_total'] = '';
        return $services;
    }
    return $services;
}

我尝试打印匹配结果,结果为

  Array ( [0] => info1 [1] => 1 ) Array ( [0] => price_total1 [1] => 1 ) 
   Array ( [0] => info2 [1] => 2 ) Array ( [0] => price_total2 [1] => 2 )

提前致谢。

4

1 回答 1

0

试试这个。短版,请勿使用preg_match

function getServices($serviceinfo) {
    $services = array();
    if (is_array($serviceinfo) && !empty($serviceinfo)) {
        foreach ($serviceinfo as $key => $value) {
            if(strpos($key, 'info') === 0){
                $services['service_'.substr($key, 4)]['info']=$value;
            }elseif (strpos($key, 'price_total') === 0){
                $services['service_'.substr($key, 11)]['price_total']=$value;
            }
        }
    }
    return $services;
}

$data = array('info1'=>'test service','price_total1'=>10,'info2'=>'test servicing','price_total2'=>5);
$service = getServices($data);
print_r($service);
于 2013-09-13T04:51:08.333 回答