PHP:从数组键中提取值

时间:2017-04-26 03:31:25

标签: 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'
    ));

显示数组后显示 -

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);

3 个答案:

答案 0 :(得分:2)

Code Snippet

您可以迭代每个密钥并检查密钥是否具有“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)

使用Explodestrpos

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

Try this code snippet here

<?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
)