Sushi
Sushi

Reputation: 676

How to separate elements from an array values on php and built new array?

i've got this array (from a csv file) :

array (
 0 => 'entity_id;commission_book;old_price;new_price',
 1 => '667;667;667;667',
 2 => '668;668;668;668'
 )

How to build a new array that looks like :

[0] : (
 'entity_id' => '667',
 'commission_book' => '667',
 'old_price' => '667',
 'new_price' => '667',
);
[1] : (
 'entity_id' => '668',
 'commission_book' => '668',
 'old_price' => '668',
 'new_price' => '668',
 )

In other words, i want to buid 2 objects using the first array, is there any way to perfom that please ? I'm trying for hours now

Upvotes: 0

Views: 26

Answers (3)

Andreas
Andreas

Reputation: 23958

$array = array(
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668');

$array[0] = explode(";",$array[0]);
$array[1] = explode(";",$array[1]);
$array[2] = explode(";",$array[2]);
$newarray = array();

for ($i=0;$i<count($array[0]);$i++){
    $newarray[0][$array[0][$i]] = $array[1][$i]; 
    $newarray[1][$array[0][$i]] = $array[2][$i]; 
}

echo "<pre>";
var_dump($array);
var_dump($newarray);
echo "</pre>";

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Short solution with array_slice and array_combine:

$from_csv = [
    0 => 'entity_id;commission_book;old_price;new_price',
    1 => '667;667;667;667',
    2 => '668;668;668;668'
];

$result = [];
$keys = explode(";", $from_csv[0]);  // header fields

foreach(array_slice($from_csv, 1) as $v){
    $result[] = array_combine($keys, explode(";", $v));
}

echo '<pre>';
var_dump($result);

// the output:
array(2) {
  [0]=>
  array(4) {
    ["entity_id"]=>
    string(3) "667"
    ["commission_book"]=>
    string(3) "667"
    ["old_price"]=>
    string(3) "667"
    ["new_price"]=>
    string(3) "667"
  }
  [1]=>
  array(4) {
    ["entity_id"]=>
    string(3) "668"
    ["commission_book"]=>
    string(3) "668"
    ["old_price"]=>
    string(3) "668"
    ["new_price"]=>
    string(3) "668"
  }

}

Upvotes: 1

arkascha
arkascha

Reputation: 42935

This is a simply but elegant way to do that:

<?php

$input = [
    0 => 'entity_id;commission_book;old_price;new_price',
    1 => '667;667;667;667',
    2 => '668;668;668;668'
];
$output = [];

// drop header entry
array_shift($input);
// process remaining entries
foreach ($input as $key=>$entry) {
    $x = &$output[$key];
    list(
        $x['entity_id'],
        $x['commission_book'],
        $x['old_price'],
        $x['new_price']
    ) = explode(';', $entry);
}


print_r($output);

The output of the above is:

Array
(
    [0] => Array
        (
            [new_price] => 667
            [old_price] => 667
            [commission_book] => 667
            [entity_id] => 667
        )

    [1] => Array
        (
            [new_price] => 668
            [old_price] => 668
            [commission_book] => 668
            [entity_id] => 668
        )

)

Upvotes: 3

Related Questions