Onilol
Onilol

Reputation: 1339

Array manipulation/remodeling

I'm reading data from a csv using fgetcsv and the output is like this:

Array(
  [0] => Array
      (
         [0] => NUMBER
         [1] => CODE
         [2] => DESCRIPTION
      )
  [1] => Array
      (
         [0] => 19
         [1] => ABC
         [2] => RANDOM DESC
      )
  [2] => Array
      (
         [0] => 56
         [1] => DEF
         [2] => ANOTHER DESC
      )
)

but since I'll do some searching based on the number I think memory wise I'd need an array like this instead:

Array(
  [19] => Array
       (
          [CODE] = ABC
          [DESCRIPTION] = RANDOM DESC
       )
  [56] => Array
       (
          [CODE] = DEF
          [DESCRIPTION] = ANOTHER DESC
       )
)

Is this the best approach or there might be something better? Also... Is there a function to do this? I'm not very PHP savy so.. please bear with me.

Upvotes: 0

Views: 55

Answers (3)

Mulan
Mulan

Reputation: 135357

Using array_reduce can make this easy for you

$result = array_reduce(array_slice($data, 1), function($ys, $x) {
  list($number, $code, $description) = $x;
  $ys[intval($number)] = array('CODE' => $code, 'DESCRIPTION' => $description);
  return $ys;
}, array());

var_dump($result);

Output

array(2) {
  [19]=>
  array(2) {
    ["CODE"]=>
    string(3) "ABC"
    ["DESCRIPTION"]=>
    string(11) "RANDOM DESC"
  }
  [56]=>
  array(2) {
    ["CODE"]=>
    string(3) "DEF"
    ["DESCRIPTION"]=>
    string(12) "ANOTHER DESC"
  }
}

Upvotes: 2

Ravinder Reddy
Ravinder Reddy

Reputation: 3879

see if this code helps you. Array can have any number of elements

// removes the header ( first element in the array)
$header = array_shift($data_array);
// iterate the array
foreach($data_array as $key=>$value){
    // check if array
if(is_array($value)){
    $search_number = $value[0];
    foreach($value as $k=>$v){   
        if($k>0){
            $new_data_array[$search_number][$header[$k]]=$v;
        }
    }
}
}

print_r($new_data_array);

Out Put

Array
(
[19] => Array
    (
        [CODE] => ABC
        [DESCRIPTION] => RANDOM DESC
    )

[56] => Array
    (
        [CODE] => DEF
        [DESCRIPTION] => ANOTHER DESC
    )

)

Upvotes: 1

Xorifelse
Xorifelse

Reputation: 7911

Something in the line like this?

foreach($firstarray as $value){
  $newarray[$value[0]] = ['code' => $value[1], 'desc' => $value[2]];
}

print_r($newarray);

However keep in mind that this code overwrites existing ID's, but you could check with: if(!isset($newarray[$value[0]])){}

But I have to be honest here. I don't see the performance benefit of using that ID as the main index ID. A sorted array should loop faster. This of course greatly depends on the size of your csv.

Upvotes: 0

Related Questions