在具有条件的给定数组的php中制作子数组

时间:2014-02-05 06:32:08

标签: php arrays sorting foreach

我有一个数组

$Info= array("Lib-1604_S1_L001_R1_001.fastq.gz", "Lib-1604_S1_L001_R2_001.fastq.gz", "Lib-1605_S1_L001_R1_001.fastq.gz", "Lib-1605_S1_L001_R2_001.fastq.gz", "Lib-1606_S1_L001_R1_001.fastq.gz");

注意Lib-1604,Lib-1605的值都有2个R1和R2值。这是常量,除R1和R2之外的任何新值都是不可能的。  我必须像下面给出的行一样做出结果吗?

Lib-1604    Lib-1604_S1_L001_R1_001.fastq.gz    Lib-1604_S1_L001_R2_001.fastq.gz
Lib-1605    Lib-1605_S1_L001_R1_001.fastq.gz    Lib-1605_S1_L001_R2_001.fastq.gz
Lib-1606    Lib-1606_S1_L001_R1_001.fastq.gz

我试过并得到了答案,代码如下。但任何新的想法???

<?php

$Info= array("Lib-1604_S1_L001_R1_001.fastq.gz", "Lib-1604_S1_L001_R2_001.fastq.gz", "Lib-1605_S1_L001_R1_001.fastq.gz", "Lib-1605_S1_L001_R2_001.fastq.gz", "Lib-1606_S1_L001_R1_001.fastq.gz");
$Info1= array();
foreach ($Info as $new)
{
    $elements = explode("_",$new);

    $data = $elements[0];
    $read = $elements[3];

    $Info1[$data][$read] = $new;
}

foreach($Info1 as $Samples=>$val)
{

    $R1_path    =   "";
    $R2_path    =   "";

    if(isset($val["R1"])){
    $R1_path    = $val["R1"];
    }
    if(isset($val["R2"])){
    $R2_path    = $val["R2"];
    }
    echo "$Samples\t$R1_path\t$R2_path<br>";

}

?>

1 个答案:

答案 0 :(得分:1)

尝试这个PHP代码我会对你有用

$Info= array("Lib-1604_S1_L001_R1_001.fastq.gz", "Lib-1604_S1_L001_R2_001.fastq.gz", "Lib-1605_S1_L001_R1_001.fastq.gz", "Lib-1605_S1_L001_R2_001.fastq.gz", "Lib-1606_S1_L001_R1_001.fastq.gz");
$arr_result = array();
foreach($Info as $val)
{
    $arr1 = explode("_",$val);
    $arr_result[$arr1[0]][] = $val;
}


foreach($arr_result as $key=>$arr_val)
{
    echo $key."    ";
    foreach($arr_val as $val)
    {
        echo $val."    ";
    }
    echo "<br/>";
}