我有这段代码:
$arrmixData = array();
$arrmixData['maintenance_request'] = array(
'is_charge_post' => '1',
'is_material_post' => '1',
'sub_maintenance_request_123456'=> array(
'is_complete_sub_task' => '0'
),
'sub_maintenance_request_123465'=> array(
'is_complete_sub_task' => '1'
));
显示数组后显示 -
Array(
[maintenance_request] => Array
(
[is_charge_post] => 1
[is_material_post] => 1
[sub_maintenance_request_123456] => Array
(
[is_complete_sub_task] => 0
)
[sub_maintenance_request_123465] => Array
(
[is_complete_sub_task] => 1
)
))
我只想要来自密钥“sub_maintenanace_request_”的id。我试图爆炸,但它不起作用。任何建议。
预期产出:
$arrSubIds = (123456,123465);
答案 0 :(得分:2)
您可以迭代每个密钥并检查密钥是否具有“sub_maintenance_request”。进一步检查它是否有数字,如果有数字,你可以存储匹配的数字。
$result
有最终结果。
试试这个:
$arrmixData = array();
$arrmixData['maintenance_request'] = array(
'is_charge_post' => '1',
'is_material_post' => '1',
'sub_maintenance_request_123456'=> array(
'is_complete_sub_task' => '0'
),
'sub_maintenance_request_123465'=> array(
'is_complete_sub_task' => '1'
)
);
$result = array();
//Itetrate on each key
foreach($arrmixData['maintenance_request'] as $key=> $value){
//check if key has 'sub_maintenance_request_' in it or not
if (strpos($key, 'sub_maintenance_request_') !== false) {
//check if key contains digits if yes then store them in $result
if (preg_match('#(\d+)$#', $key, $matches)) {
$result[] = array_shift( $matches );
}
}
}
答案 1 :(得分:1)
使用Explode
和strpos
1)strpos检查当前密钥是sub_maintenance_request_
还是
2)如果它是sub_maintenance_request_
,则使用"_"
下划线爆炸。
3)使用array_pop()
<?php
$arrSubIds=array();
foreach($arrmixData['maintenance_request'] as $key=>$row)
{
if(strpos($key, 'sub_maintenance_request_') !== false)
{
$arrSubIds[] = array_pop(explode('_',$key));
}
}
print_r($arrSubIds);
?>
<强>输出:强>
Array
(
[0] => 123456
[1] => 123465
)
答案 2 :(得分:0)
我们正在使用strpos
函数在字符串中检索substring
的位置,并使用ltrim
函数从左侧修剪substring
。
<?php
$arrmixData = array();
$arrmixData['maintenance_request'] = array(
'is_charge_post' => '1',
'is_material_post' => '1',
'sub_maintenance_request_123456' => array(
'is_complete_sub_task' => '0'
),
'sub_maintenance_request_123465' => array(
'is_complete_sub_task' => '1'
));
$result=array();
foreach($arrmixData["maintenance_request"] as $key => $value)
{
if(strpos($key, "sub_maintenance_request_")===0)//getting the position of substring
{
$result[]=ltrim($key,"sub_maintenance_request_");trimmed substring to retrieve last digits
}
}
print_r($result);
<强>输出:强>
Array
(
[0] => 123456
[1] => 123465
)