我有一个关联数组。在这个数组中,一些键的前缀是“suf_”。我如何使用这些后缀键和值创建一个新数组?见下面的例子
Array
(
[buildings_sum] =>
[accidental_damage] => 0
[landslip_cover] => 0
[loss_of_rent] =>
[loss_period] =>
[contents_sum] =>
[suf_household_contents_sum] =>
[damage_cover] => 0
[suf_tobacco_stock_sum] =>
[stock_sum] =>
[suf_buisness_interruption] => gb
[suf_buisness_interruption_indemnity] => 24 Months
[suf_increased_cost] => vb
[suf_increased_cost_indemnity] => 24 Months
[employer_liability] => 0
[liability_sum] => 2000000
[property_owner_liability] => 1000000
[goods_sum] => hvb
[freezer_stock] => bv
[money_night_safe] => vb
[money_locked_safe] => bv
[money_not_locked_safe] => cv
[private_dwelling_money] => fcv
[suf_change_machine_money] => cfv
[suf_gaming_machine_money] => 0
[personal_accident] => cfv
[glass] => cv
[book_debts] => cv
[suf_cover_guest] => 0
[terrorism_cover] => 0
[legal_expenses_cover] => 0
[loss_of_licence] => 0
[risks_cover] => 0
[voluntary_excess] => 250
[compulsory_excess] => h
)
答案 0 :(得分:1)
使用foreach
循环和preg_match
。这是一个以youd数据为例的工作示例。
$data_array = array();
$data_array['stock_sum'] = '';
$data_array['suf_buisness_interruption'] = 'gb';
$data_array['suf_buisness_interruption_indemnity'] = '24 Months';
$data_array['suf_increased_cost'] = 'vb';
$data_array['suf_increased_cost_indemnity'] = '24 Months';
$data_array['employer_liability'] = 0;
$data_array['liability_sum'] = 2000000;
$data_array['property_owner_liability'] = 1000000;
$data_array['goods_sum'] = 'hvb';
$data_array['freezer_stock'] = 'bv';
$data_array['money_night_safe'] = 'vb';
$data_array['money_locked_safe'] = 'bv';
$suf_array = array();
foreach ($data_array as $key => $value) {
if (preg_match('/^suf_/', $key)) {
$suf_array[$key] = $value;
}
}
echo '<pre>';
print_r($suf_array);
echo '</pre>';
答案 1 :(得分:0)
遍历数组并获取密钥中suf_
部分的所有元素:
$new_array = array();
foreach ($array as $key => $value) {
if (substr($key, 0, 4) == 'suf_') {
$new_array[$key] = $value;
}
}
print_r($new_array);