如何使用PHP

时间:2018-02-22 03:27:56

标签: php arrays csv explode

如何使用不同的id提取数组注意css_id点击图片以获取更多样本

[0] => Array(
        [cses_id] => 54
        [ccc_id] => 1157
        [csh_id] => 206
        [css_id] => 441,442
        [sai_id] => 12213

    )

expedted output below
*********************************************
[0] => Array(
        [cses_id] => 54
        [ccc_id] => 1157
        [csh_id] => 206
        [css_id] => 441
        [sai_id] => 12213

    )

[1] => Array(
        [cses_id] => 54
        [ccc_id] => 1157
        [csh_id] => 206
        [css_id] => 442
        [sai_id] => 12213

    )

click here for another sample

1 个答案:

答案 0 :(得分:2)

此任务可以通过多种方式执行。这只是一种适用于您的样本输入数组的方法。请参阅内联注释以获取解释。

代码:(Demo

$array=['cses_id'=>'54','ccc_id'=>'1157','csh_id'=>'206','css_id'=>'441,442','sai_id'=>'12213'];

$count=0;

// convert each comma-separated value to an array of values & store the max comma count
$multi=array_map(function($v)use(&$count){$count=max($count,substr_count($v,',')); return explode(',',$v);},$array);
++$count;  // increment to know how many "columns" of values exist
for($col=0; $col<$count; ++$col){
    $temp=[];
    foreach($multi as $key=>&$val){
        $temp[$key]=(sizeof($val)>1?array_shift($val):current($val));  // take off the front element until only one is left (and repeat the use of final value)
    }
    $result[]=$temp;  // store this batch of columnar data
}
var_export($result);

输出:

array (
  0 => 
  array (
    'cses_id' => '54',
    'ccc_id' => '1157',
    'csh_id' => '206',
    'css_id' => '441',
    'sai_id' => '12213',
  ),
  1 => 
  array (
    'cses_id' => '54',
    'ccc_id' => '1157',
    'csh_id' => '206',
    'css_id' => '442',
    'sai_id' => '12213',
  ),
)

这是获得相同结果的另一种方法:(Demo

$array=['cses_id'=>'54','ccc_id'=>'1157','csh_id'=>'206','css_id'=>'441,442','sai_id'=>'12213'];
do {
    $stop=true;                      // default to stop after each iteration
    $temp=[];                        // clear the $temp variable
    foreach($array as $key=>&$val){  // iterate associate array, modify $val by reference
        $parts=explode(',',$val,2);  // break the value on the first comma only
        $temp[$key]=$parts[0];       // associatively store first value to the temp array
        if(sizeof($parts)>1){        // if there was a comma this iteration...
            $stop=false;             // tell the loop to do another iteration
            $val=$parts[1];          // modify $array by overwriting $val with the remaining comma-separated value
        }
    }
    $result[]=$temp;                 // this this iteration's temporary array in the result array
} while(!$stop);                     // iterate while there are any commas still in the any of the elements

var_export($result);                 // print to screen