如何从PHP上的数组值中分离元素并构建新数组?

时间:2016-02-07 18:42:03

标签: php arrays

我有这个数组(来自csv文件):

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

如何构建一个类似于:

的新数组
[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',
 )

换句话说,我想用第一个数组来建立2个对象,请问有什么方法可以吗?我现在正试着几个小时

3 个答案:

答案 0 :(得分:3)

这是一种简单而优雅的方式:

<?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);

以上的输出是:

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
        )

)

答案 1 :(得分:1)

array_slicearray_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"
  }

}

答案 2 :(得分:0)

$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>";