Reputation: 3093
I would like to replace all numerical keys in the multidimensional array $aValues
with a textual equivalent stored in $aKeyNames
.
$aKeyNames = array(0 => 'foo', 1 => 'bar');
$aValues = array(
0 => array( 0 => 'content relating to foo', 1 => 'content relating to bar' ),
1 => array( 0 => 'content relating to foo', 1 => 'content relating to bar')
);
The desired output;
array (size=2)
0 =>
array (size=2)
'foo' => string 'content relating to foo' (length=23)
'bar' => string 'content relating to bar' (length=23)
1 =>
array (size=2)
'foo' => string 'content relating to foo' (length=23)
'bar' => string 'content relating to bar' (length=23)
To achieve this I've written the following working code;
foreach ($aValues as $iValuePos => $aValue) {
foreach ($aValue as $iKey => $sTempValue){
$aValues[$iValuePos][ $aKeyNames[$iKey] ] = $sTempValue;
unset($aValues[$iValuePos][$iKey]);
}
}
My concern is that $aValues
is very large. Is there a more efficient way to achieve this?
Please note this question is different to the one provided as a duplicate due to the use of a multidimensional array.
Upvotes: 0
Views: 70
Reputation: 78984
I haven't bench-marked but it should be faster:
$aValues = array_map(function($v) use ($aKeyNames) {
return array_combine($aKeyNames, $v);
}, $aValues);
Another alternative using a reference &
to the value:
foreach($aValues as &$v) {
$v = array_combine($aKeyNames, $v);
}
Upvotes: 1
Reputation: 139
Try this:
$aKeyNames = array(0 => 'foo', 1 => 'bar');
$aValues = array(
0 => array( 0 => 'content relating to foo', 1 => 'content relating to bar' ),
1 => array( 0 => 'content relating to foo', 1 => 'content relating to bar')
);
foreach ($aValues as $iValuePos => $aValue) {
$aValues[$iValuePos] = array_combine($aKeyNames, $aValue);
}
Upvotes: 1