vignesh.D
vignesh.D

Reputation: 776

How to create an array based on value in PHP?

I have an array like this

  Array
(
    [0] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf
    [1] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf
    [2] => 123_bms_for__on__(10-06-2015_18-36).pdf
)

I want to convert this into multidimensional array based on its value such as

  Array
(
    [dr] => Array
        (
            [0] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf
            [1] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf
        )
    [bms] => Array
        (
            [0] => 123_bms_for__on__(10-06-2015_18-36).pdf
        )
)  

based on name after first underscore (bms,dr) like....... Please help me to achieve this

Upvotes: 2

Views: 1742

Answers (5)

Azri Jamil
Azri Jamil

Reputation: 2404

You can use array_reduce function and regex matching for elegant & lesser code.

$array = array(
    '0'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf',
    '1'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf',
    '2'=>'123_bms_for__on__(10-06-2015_18-36).pdf'
);

$result = array_reduce($array, function($prod, $current){
    preg_match('/(?<=^123_)\w+(?=_for\w+)/',$current,$match);
    $prod[$match[0]][] = $current;
    return $prod;
}, []);

Will produce the following result.

array(2) {
  [0]=>
  string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf"
  [1]=>
  string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf"
}
array(1) {
  [0]=>
  string(39) "123_bms_for__on__(10-06-2015_18-36).pdf"
}

Using square bracket require PHP 5.4 above, you can replace with array() instead for lower version of PHP.

Upvotes: 2

93Ramadan
93Ramadan

Reputation: 343

To solve this without a loop, it would be smart to use a function along with built in Array Filter function.

Here's another possible solution - which seems a little cooler I suppose;

<?php

// ####################
// GLOBAL VARIABLES DEFINITION    
// ####################
// Store Pattern Here = Used to Define Array at the end
global $Array_IDs; 
$Array_IDs = array();
// Store Variables With Header Pattern (ID) in this area
global $Array_Values; 
$Array_Values = array();

// ####################
// FUNCTION DEFINITION
// ####################
// FUNCTION TO SPLIT ARRAY
function Get_ID($variable){
    // ACCESS GLOBALS
    global $Array_IDs; 
    global $Array_Values; 

    // GET CURRENT VARIBALE - EXPLODE TO EXTRACT PATTERN AS ID
    $Temp_Parts = explode("_", $variable);

    // CHECK IF IDENTIFIER IS ALREADY FOUND (STORED IN ARRAY_ID)
    if (in_array($Temp_Parts[1], $Array_IDs)){
        // ID ALREADY HAS SUB-ARRAY CREATED
        // JUST APPEND VARIABLE
        $Array_Values[$Temp_Parts[1]][] = $variable;
    }else{
        // ADD ID TO Array_IDs
        $Array_IDs[] = $Temp_Parts[1];
        // Create New ARRAY with HEADER AS PATTERN - ID
        $Array_Values[$Temp_Parts[1]][] = $variable;
    }
}

// ####################
// CODE STARTS HERE == ONLY THREE LINES ;)
// ####################
$Start_Array = array('123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf','123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf','123_bms_for__on__(10-06-2015_18-36).pdf');
array_filter($Start_Array,"Get_ID");
print_r($Array_Values);

?>

Give it a try and let me know how it goes, the output is as requested ;)

Upvotes: 2

David Demetradze
David Demetradze

Reputation: 1371

$basicArray = array(); //It Stores All The Elements
$firstArray = array(); //It will store array elements of first type
$secondArray = array(); //It will store array elements of second type
for($i = 0; $i < count($basicArray); $i++)
{
    $elementArray = explode("_", $basicArray[i]);
    if($elementArray[1] == "dr")
        array_push($firstArray, $basicArray[i]);
    else if($elementArray[1] == "bms")
        array_push($secondArray, $basicArray[i]);
}
$finalArray = array(); 
array_push($finalArray, $firstArray, $secondArray);

Upvotes: -2

Ghanshyam Katriya
Ghanshyam Katriya

Reputation: 1081

please find below code as per your requirement.

<?php
$array = array(
    '0'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf',
    '1'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf',
    '2'=>'123_bms_for__on__(10-06-2015_18-36).pdf'
);

$dr_array = array();
$bms_array = array();
foreach($array as $val){
    $str_explode = explode("_",$val);

    if($str_explode[1]=="dr"){
        $dr_array[] = $val;
    }
    else if($str_explode[1]=="bms"){
        $bms_array[] = $val;
    }
}
var_dump($dr_array);
var_dump($bms_array);
?>

Output :

array(2) {
  [0]=>
  string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf"
  [1]=>
  string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf"
}
array(1) {
  [0]=>
  string(39) "123_bms_for__on__(10-06-2015_18-36).pdf"
}

Thanks.

Upvotes: 1

Peter
Peter

Reputation: 9113

I would do the following:

$newArray = array();
foreach ($array as $key => $value) {
    $parts = explode('_', $value);
    $newArray[$parts[1]][] = $value;
}

print_r($newArray); 

Upvotes: 19

Related Questions