[英]Create multi-dimensional array from another multi-dimensional array PHP
Lets say I have a multi-dimensional array like this : 可以说我有一个像这样的多维数组:
$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
)
);
And I want to create a new multi-dimensional array only using specific objects : 我只想使用特定对象创建一个新的多维数组:
$newarray = array(
0 => array(
'fruit' => 'apple',
'amount' => 50
),
1 => array(
'fruit' => 'orange',
'amount' => 25
),
2 => array(
'fruit' => 'banana',
'amount' => 7
)
);
How would I do this? 我该怎么做? I've read a few different things and it seems like
array_map
or array_column
might be the answer but I haven't found an example that fits my situation. 我读过一些不同的东西,似乎
array_map
或array_column
可能是答案,但我还没有找到适合我情况的示例。
I've got as far as : 我到目前为止:
$newarray = array();
foreach ($results as $result) {
if (!empty($result['fruit'])) {
// create new array here but how do I specify the key => values?
}
}
This is suitable if the keys are fixed and you don't have too many of them: 如果键是固定的,并且您没有太多键,则这是合适的:
$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);
Gives: 得到:
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
in any case this is what you wan't correct? 无论如何,这是您不正确的?
foreach ($results as $key) {
unset ($results[$key]['colour']);
}
print_r($results);
Output: 输出:
Array
(
[0] => Array
(
[fruit] => apple
[amount] => 50
)
[1] => Array
(
[fruit] => orange
[amount] => 25
)
[2] => Array
(
[fruit] => banana
[amount] => 7
)
)
Set your keys on "$keys_to_search". 将密钥设置在“ $ keys_to_search”上。 Is better than use unset.
胜过使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.