0

I have an array like below.

$arr=array('0_1','0_3','1_2',1_1','4_1');

can i divide it into

$arr[0][1]='0_1';
$arr[0][3]='0_3';

... Thanks.

1
  • 2
    What you have tried so far post your attempts too Commented Mar 31, 2016 at 9:51

3 Answers 3

4
$newArray = [];
foreach ($arr as $item) {
    $items = explode('_', $item);
    $newArray[$items[0]][$items[1]] = $item;
}
var_dump($newArray);
exit();

This should do the trick. You should have a look at the explode function

Sign up to request clarification or add additional context in comments.

Comments

2

Another way to do this without foreach loop. :->

$arr = array('0_1','0_3','1_2','1_1','4_1');
$result = [];
array_walk($arr,function($v,$k)use (&$result){
    $data = explode("_",$v);
    $result[$data[0]][$data[1]] = $v;
});
print_r($result);

1 Comment

Thanks for your solution. but It seem the first solution is more readable and simple.
1
$arrv = array('0_1','0_3','1_2','1_1','4_1');
$newArray = [];
array_walk($arrv,function($value,$key){
    global $newArray;
    $indexArray = explode("_",$value);
    $newArray[$indexArray[0]][$indexArray[1]] = $value;
});
var_dump($newArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.