从另一个多维数组PHP创建多维数组

时间:2018-04-12 22:39:15

标签: php arrays multidimensional-array

假设我有一个像这样的多维数组:

$results = array(
    0 => array(
        'fruit' => 'apple',
        'colour' => 'green',
        'amount' => 50
    ),
    1 => array(
        'fruit' => 'orange',
        'colour' => 'orange',
        'amount' => 25
    ),
    2 => array(
        'fruit' => 'banana',
        'colour' => 'yellow',
        'amount' => 7
    )
);

我想仅使用特定对象创建一个新的多维数组:

$newarray = array(
    0 => array(
        'fruit' => 'apple',
        'amount' => 50
    ),
    1 => array(
        'fruit' => 'orange',
        'amount' => 25
    ),
    2 => array(
        'fruit' => 'banana',
        'amount' => 7
    )
);

我该怎么做?我已经阅读了一些不同的内容,似乎array_maparray_column可能是答案,但我找不到符合我情况的例子。

我到目前为止:

$newarray = array();
foreach ($results as $result) {
    if (!empty($result['fruit'])) {
      // create new array here but how do I specify the key => values?
    }
}

3 个答案:

答案 0 :(得分:2)

如果按键已修复并且您没有太多按键,则此功能非常合适:

$results = array(
    0 => array(
        'fruit' => 'apple',
        'colour' => 'green',
        'amount' => 50
    ),
    1 => array(
        'fruit' => 'orange',
        'colour' => 'orange',
        'amount' => 25
    ),
    2 => array(
        'fruit' => 'banana',
        'colour' => 'yellow',
        'amount' => 7
    )
);

$new = array();
foreach($results as $value){
    $new[] = array(
        'fruit' => $value['fruit'],
        'amount' => $value['amount']
    );
}
var_dump($new);

给出:

array (size=3)
  0 => 
    array (size=2)
      'fruit' => string 'apple' (length=5)
      'amount' => int 50
  1 => 
    array (size=2)
      'fruit' => string 'orange' (length=6)
      'amount' => int 25
  2 => 
    array (size=2)
      'fruit' => string 'banana' (length=6)
      'amount' => int 7

答案 1 :(得分:1)

无论如何这是你不正确的?

foreach ($results as $key) {
    unset ($results[$key]['colour']);
}

print_r($results);

输出:

Array
(
[0] => Array
    (
        [fruit] => apple
        [amount] => 50
    )

[1] => Array
    (
        [fruit] => orange
        [amount] => 25
    )

[2] => Array
    (
        [fruit] => banana
        [amount] => 7
    )

)

答案 2 :(得分:0)

将您的密钥设置为“$ keys_to_search”。 比使用unset更好。

$keys_to_search = ['fruit' => '','colour' => ''];

$results = array(
    0 => array(
        'fruit' => 'apple',
        'colour' => 'green',
        'amount' => 50
    ),
    1 => array(
        'fruit' => 'orange',
        'colour' => 'orange',
        'amount' => 25
    ),
    2 => array(
        'fruit' => 'banana',
        'colour' => 'yellow',
        'amount' => 7
    )
);




foreach($results as $key => $value){
    $result[] = array_intersect_key($value, $keys_to_search);  
}

print_r($result);