0

I have two arrays, one that contains all options, and a second one that contains the default values.

The options arrays looks like 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 I have another array that contains default value, and it looks like this

$defaults= array(
   "SeriesA" => "A-002",
   "SeriesB" => "B-001",
);

What I would like to end up with is one array that contains all info, is there a way that I can map both arrays and get one array that will look like 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
        )
    ),
);
2
  • Just make a foreach loop wich is testing wich array in the series array is the default, and put a "default" => true value in the array. In every other array in a series array, put a "default" => false value. Commented Jul 6, 2016 at 11:03
  • Is this coming from a database? If so you can do this all in the SQL. Commented Jul 6, 2016 at 11:41

1 Answer 1

1

Here is two ways to do it:

Make a function, which accepts two args and check value in a loop with defaults, add defaults, and returns new array, or edit array, passing it by reference:

function awesomeName(&$options, $defaults) {
    foreach ($options as $k => &$values) {
        foreach ($values as &$AsAndBs) {
            $AsAndBs['default'] = $AsAndBs['value'] == $defaults[$k];
        }
    }
}

Using array_walk() function with anonymous function:

array_walk($options, function (&$v, $k) use ($defaults) {
    $series = $k;
    foreach ($v as &$series_contents) {
        $series_contents['default'] = $series_contents['value'] == $defaults[$series];
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.