Vineesh K S
Vineesh K S

Reputation: 1964

Make subarray in php from given array with conditions

I have an array

$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");

Note the values Lib-1604, Lib-1605, both have 2 values with R1 and R2 . This are constants any new value other than R1 and R2 is not possible. I have to make a result like rows given below, any idea?

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

I have tried and got the answer, the code is give below. But any new Idea???

<?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>";

}

?>

Upvotes: 0

Views: 360

Answers (1)

Satish Sharma
Satish Sharma

Reputation: 9635

try this php code i thing it will useful for you

$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/>";
}

Upvotes: 1

Related Questions