- This topic is empty.
-
AuthorPosts
-
January 7, 2012 at 7:46 pm #36017jacorreParticipant
I’m trying to change array keys to lowercase. I tried using array_change_key_case but it’s not working and I think it’s because I’m using arrays within arrays. Here is an example:
array (
[0] = array
(
[Amount] => 1
[Measurement] => Cup
[Ingredient] => Sugar
[Notes] => Some comments
)
[1] = array
(
[Amount] => 2
[Measurement] => Cups
[Ingredient] => Flour
[Notes] => Some comments
)
)I’m trying to get it so that the keys switch to lowercase like:
array (
[0] = array
(
[amount] => 1
[measurement] => Cup
[ingredient] => Sugar
[notes] => Some comments
)
[1] = array
(
[amount] => 2
[measurement] => Cups
[ingredient] => Flour
[notes] => Some comments
)
)Doesn’t seem to work with array_change_key_case?
January 9, 2012 at 11:57 am #94341jacorreParticipantI did see that function but didn’t seem to work for me. I may have been using it wrong. I’ll try again and see. Thanks!
January 9, 2012 at 12:32 pm #94343jamygoldenMember$a = array(
array(
'Amount' => 1,
'Measurement' => 'Cup',
'Ingredient' => 'Sugar',
'Notes' => 'Some comments'
),
array(
'Amount' => 2,
'Measurement' => 'Cups',
'Ingredient' => 'Flour',
'Notes' => 'Some comments'
)
);
function strToLowerArray ( $vals ) {
return strtolower( $vals );
}
foreach( $a as $arr ) {
$b[] = array_map("strToLowerArray", $arr);
}
print_r($b);
?>Edit: Oh you said the KEY should be lowercase…
$a = array(
array(
'Amount' => 1,
'Measurement' => 'Cup',
'Ingredient' => 'Sugar',
'Notes' => 'Some comments'
),
array(
'Amount' => 2,
'Measurement' => 'Cups',
'Ingredient' => 'Flour',
'Notes' => 'Some comments'
)
);
foreach( $a as $arr ) {
print_r(array_change_key_case($arr, CASE_LOWER));
echo '
';
}
?>January 9, 2012 at 12:43 pm #94344jacorreParticipantThanks jamy_za I like that method better. Less code! And testing it online seems to work nicely. Thanks again!
March 30, 2013 at 4:06 am #130191nphp101Memberfunction arrIndexLowerCase($arr = null){
$arr = array_change_key_case($arr,CASE_LOWER);
$newArr = $arr;
foreach ($arr as $k => $v){
if (is_array($v)){
$newArr[$k] = $this->arrIndexLowerCase($v);
}
}
return $newArr;
}March 30, 2013 at 4:08 am #130192nphp101Memberrecursive function will do the magic tricks for multi-arrays, as stated above.
March 30, 2013 at 6:45 am #130204CrocoDillonParticipantOld post but you don’t even need to copy the array
function array_change_key_case_recursive($input, $case = null) {
$case = $case ?: CASE_LOWER;
$input = array_change_key_case($input, $case);
foreach ($input as $key => $val) {
if (is_array($val))
$input[$key] = array_change_key_case_recursive($val, $case);
}
} -
AuthorPosts
- The forum ‘Back End’ is closed to new topics and replies.