简体   繁体   中英

Convert 1d array to 2d in php

I have a 1d array as follows:

$arr = [
    'itemName0' => "first Item",
    'itemDesc0' => "first item's description",
    'itemName1' => "second item",
    'itemDesc1' => "third item's description",
];

and i would like to convert it to a 2d array as follows

$arr = [
    0 => [
        'itemName' => "first Item",
        'itemDesc' => "first item's description",
    ],
    1 => [
        'itemName' => "second item",
        'itemDesc' => "Second item's description",
    ],
];

Actually i have data coming from an api response which contains other details apart from the item.....{index} eg

$arr = [
    'status' => 'success',
    'blahblah' => 'this is just a test',
    'itemName0' => "first Item",
    'itemDesc0' => "first item's description",
    'itemName1' => "second item",
    'itemDesc1' => "third item's description",
];

but i need only the item data.

i have tried to use array_map as follows to get the items but could not..

array_map(function($value, $key){ strpos($key, 'item') === false ? false : $value;  }, $arr));

im still trying.. anyideas would be really helpful

You can try this -

$arr = [
    'itemName0' => "first Item",
    'itemDesc0' => "first item's description",
    'itemName1' => "second item",
    'itemName2' => "second item's description",
];

$new = [];
foreach($arr as $key => $value) {
   $index = sscanf($key, '%[A-Za-z]%d');
   if(strpos($key, 'item') === 0) {
      $new[$index[1]][$index[0]] = $value;
   }
}

Output

array(3) {
  [0]=>
  array(2) {
    ["itemName"]=>
    string(10) "first Item"
    ["itemDesc"]=>
    string(24) "first item's description"
  }
  [1]=>
  array(1) {
    ["itemName"]=>
    string(11) "second item"
  }
  [2]=>
  array(1) {
    ["itemName"]=>
    string(25) "second item's description"
  }
}
$arr = [
    'itemName0' => "first Item",
    'itemDesc0' => "first item's description",
    'itemName1' => "second item",
    'itemName2' => "third item's description",
    'testKey1' => "Should be ignored",
    'itemData' => "No numeric, so should also be ignored"
];

$newArray = [];
foreach($arr as $key => $value) {
    list($keyName, $keyNumber) = sscanf($key, 'item%[A-Za-z]%d');
    if (!is_null($keyNumber)) {
        $newArray[$keyNumber]['item'.$keyName] = $value;
    }
}

var_dump($newArray);

Demo

The simplest i can make is,

$process = array_filter($arr, function($key){
               return (strpos($key, 'itemName') !== false && ctype_digit(substr($key, 8)))
                      || 
                      (strpos($key, 'itemDesc') !== false && ctype_digit(substr($key, 8)));
           }, ARRAY_FILTER_USE_KEY);

$final = [];

foreach ($process as $key => $value)
{
    $final[substr($key, 8)][substr($key, 0, 8)] = $value;
}

First, create an empty multi-dimensional array:
$multi_arr = array();

Then, traverse the original array,

foreach($arr as $key => $val) { <br/>
    //get last character from key<br/>
    $k = substr($key, -1);<br/>
    //get key index value from original key by removing last character<br/>
    $index = rtrim($key, $k);<br/>
    //Push values to multi dimensional array<br/>
    $multi_arr[$k][$index] = $val;<br/>
}

Using Array Chunk method is the easiest of all

$input_array = array('a', 'b', 'c', 'd', 'e','f');
print_r(array_chunk($input_array, 2));  

output:

Array
(
 [0] => Array
    (
        [0] => a
        [1] => b
    )

 [1] => Array
    (
        [0] => c
        [1] => d
    )

 [2] => Array
    (
        [0] => e
        [1] => f
    ) 
)

It's maybe too late to answer, but I've made a function to split arrays into as groups as you like.

function SplitInto($array, $groups = 2)
{
   $members = count($array) / $groups;
   if (count($array) % $groups) $members = (int)(count($array) / $groups) + 1;
   return array_chunk($array, $members);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM