1

我有一个关联数组。在这个数组中,一些键具有前缀“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
)
4

2 回答 2

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>';
于 2013-02-01T13:32:44.700 回答
0

遍历数组并获取所有suf_在键中包含该部分的元素:

$new_array = array();

foreach ($array as $key => $value) {
    if (substr($key, 0, 4) == 'suf_') {
        $new_array[$key] = $value;
    }
}

print_r($new_array);
于 2013-02-01T12:51:21.563 回答