I have this code:
$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'
));
After displaying the array it shows -
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
)
))
I want only id from the key "sub_maintenanace_request_". I tried for explode but its not work. Any suggestions.
Expected output:
$arrSubIds = (123456,123465);
Here we are using strpos
function to retrieve position of substring
with in a string and ltrim
function to trim a substring
from the left.
<?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);
Output:
Array
(
[0] => 123456
[1] => 123465
)
use Explode
and strpos
1) strpos to check current key is sub_maintenance_request_
or not
2) if it's sub_maintenance_request_
then use explode by "_"
underscore.
3) Get the last value from exploded array using 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);
?>
Output:
Array
(
[0] => 123456
[1] => 123465
)
You can iterate on each key and check if key has 'sub_maintenance_request' or not. Further you check if it has digit or not, if it has digit you can store matched digit.
$result
has the final result.
Try this :
$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 );
}
}
}