Reputation: 117
I am working on an array and I would like to get all the arrays between two values of an array eg
$fields = array(
'a' => array(
'name' => 'username',
'type' => 'text',
),
'b' => array(
'name' => 'birthday',
'type' => 'text',
),
'c' => array(
'name' => 'address',
'type' => 'text',
),
'd' => array(
'name' => 'password',
'type' => 'text',
),
);
So that given username
and password
I want to get the following
'b' => array(
'name' => 'birthday',
'type' => 'text',
),
'c' => array(
'name' => 'address',
'type' => 'text',
),
Simply because it comes after the array with the value of username
and before the array with value of password
.
Upvotes: 0
Views: 414
Reputation: 79014
You can extract the name
values into an array, search that and slice using the search result positions:
$names = array_column($fields, 'name');
$result = array_slice($fields, $i=array_search('username', $names)+1,
array_search('password', $names)-$i);
Upvotes: 0
Reputation: 6016
function getArraysBetweenNames($name1, $name2, $array)
{
$return = [];
$foundName1 = false;
foreach ($array as $key => $item) {
if ($foundName1) {
if ($item["name"] == $name2)
break;
$return[$key] = $item;
} elseif ($item["name"] == $name1) {
$foundName1 = true;
}
}
return $return;
}
print_r(getArraysBetweenNames("username", "password", $fields));
Upvotes: 0
Reputation: 34924
Simply loop with two condition like below
$start = "username";
$end = "password";
$new = array();
$flag = false;
foreach($fields as $key=>$value){
if($value["name"] == $start){
$flag = true;
continue;
}
if($value["name"] == $end){
break;;
}
if($flag){
$new[$key] = $value;
}
}
print_r($new);
Live demo : https://eval.in/879235
Upvotes: 1
Reputation: 2211
$fields = array(
'a' => array(
'name' => 'username',
'type' => 'text',
),
'b' => array(
'name' => 'birthday',
'type' => 'text',
),
'c' => array(
'name' => 'address',
'type' => 'text',
),
'd' => array(
'name' => 'password',
'type' => 'text',
),
);
if you want b,c array from the fields you just
echo $fields[b][name];
echo $fields[b][type];
echo $fields[c][name];
echo $fields[c][type];
Upvotes: -1