PHP array merge / map of two arrays -
i have 2 arrays, 1 contains options, , second 1 contains default values.
the options arrays looks this:
$options = array( "seriesa" => array( "a1" => array( "text" => "a1", "value" => "a-001" ), "a2" => array( "text" => "a2", "value" => "a-002" ) ), "seriesb" => array( "b1" => array( "text" => "b2", "value" => "b-001" ), "b2" => array( "text" => "b2", "value" => "b-002" ) ), );
and have array contains default value, , looks this
$defaults= array( "seriesa" => "a-002", "seriesb" => "b-001", );
what end 1 array contains info, there way can map both arrays , 1 array this:
$options = array( "seriesa" => array( "a1" => array( "text" => "a1", "value" => "a-001", "default" => false ), "a2" => array( "text" => "a2", "value" => "a-002", "default" => true ) ), "seriesb" => array( "b1" => array( "text" => "b2", "value" => "b-001", "default" => true ), "b2" => array( "text" => "b2", "value" => "b-002", "default" => false ) ), );
here 2 ways it:
make function, accepts 2 args , check value in loop defaults, add defaults, , returns new array, or edit array, passing reference:
function awesomename(&$options, $defaults) { foreach ($options $k => &$values) { foreach ($values &$asandbs) { $asandbs['default'] = $asandbs['value'] == $defaults[$k]; } } }
using array_walk() function anonymous function:
array_walk($options, function (&$v, $k) use ($defaults) { $series = $k; foreach ($v &$series_contents) { $series_contents['default'] = $series_contents['value'] == $defaults[$series]; } });
Comments
Post a Comment