1

I want to apologize in advanced if this was already asked, I'm not exactly sure what this would be called.


I'm storing data from a form into a MongoDB database and I'd like to create defined key-value pairs to make sorting easier.

Using this code I am able to do this with a one-dimensional array, but it does not work with multidimensional arrays:

/* $array = The array */
$new_array = array();

foreach ($array as $key => $value) {
    array_push($new_array, array(
        'name' => $key,
        'value' => $value
    ));
}

Example:

Input array:

Array
(
    [email] => [email protected]
    [name] => John
    [sports] => Array
        (
            [outdoor] => Array
                (
                    [0] => Football
                    [1] => Baseball
                )

            [indoor] => Array
                (
                    [0] => Basketball
                    [1] => Hockey
                )
        )
)

Output array:

Array
(
    [0] => Array
        (
            [name] => email
            [value] => [email protected]
        )

    [1] => Array
        (
            [name] => name
            [value] => John
        )

    [2] => Array
        (
            [name] => sports
            [value] => Array
                (
                    [outdoor] => Array
                        (
                            [0] => Football
                            [1] => Baseball
                        )

                    [indoor] => Array
                        (
                            [0] => Basketball
                            [1] => Hockey
                        )
                )
        )
)

Notice how it stops at the sports value array and does not change the array within it. How can I continue this pattern throughout all the arrays within it?

6
  • This isn't a code-writing service, you have to give it a try yourself and post your code. Commented May 25, 2013 at 20:25
  • @Barmar Sure. Right now I'm able to do this with a one-dimensional array. I will post the code in a minute. Commented May 25, 2013 at 20:27
  • you mean like json_decode($array,true)? Commented May 25, 2013 at 20:28
  • @Dave Chen That is what my input is array is. I now need to convert that to the above example. Commented May 25, 2013 at 20:39
  • 1
    Provide the example of multidimensional array and the result that you with you get Commented May 25, 2013 at 20:50

3 Answers 3

3

You can use recursion:

function keyValue($array){
  $new_array = array();

  foreach ($array as $key => $value) {
      array_push($new_array, array(
          'name' => $key,
          'value' => is_array($value) ? keyValue($value) : $value
      ));
  }

  return $new_array;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This almost works as desired, however the last array in the "tree" (the deepest) should just be Array([name] => outdoor [value] => Array([0] => Football [1] => Baseball)). I will just check to see if here is an array in the array, and will stop if there isn't. Thanks!
2

Try this on for size:

$array = array(
    'email' => '[email protected]',
    'name' => 'John',
    'sport' => array('Soccor', 'Hockey')
);

$func = function($value, $key) {

     $return = array();
     $return['name'] = $key;
     $return['value'] = $value;


    return $return;
};

$parsed = array_map($func, $array, array_keys($array));

For me, this returned:

   array(3) {
  [0]=>
  array(2) {
    ["name"]=>
    string(5) "email"
    ["value"]=>
    string(14) "[email protected]"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(4) "name"
    ["value"]=>
    string(4) "John"
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(5) "sport"
    ["value"]=>
    array(2) {
      ["outdoor"]=>
      array(2) {
        [0]=>
        string(8) "Football"
        [1]=>
        string(8) "Baseball"
      }
      ["indoor"]=>
      array(2) {
        [0]=>
        string(10) "Basketball"
        [1]=>
        string(6) "Hockey"
      }
    }
  }
}

1 Comment

Thanks! This works as well but, like my first example, doesn't work recursively.
0

It is pretty simple to turn associative arrays to JSON objects (StdClass) and vice versa, preserving native data types (int, float, bool). Here's my attempt:

To Key-Value Array

function toKeyValue($values)
{
    $result = [];

    foreach ($values as $key => $value)
    {
        if (is_array($value)) {
            $result[$key] = toKeyValue($value);
        } elseif (is_object($value)) {
            $result[$key] = toKeyValue((array) $value);
        } else {
            $result[$key] = $value;
        }
    }

    return $result;
}

To JSON Object

function toJson($values)
{
   return json_decode(json_encode($values));
}

$values should always be an array.

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.