0

I have this associative array structure:

$multiArray = array(
                 'key1' => array(1, 2, 3, 4),                
                 'key2' => array(5, 6, 7, 8),
                 'key3' => array(9, 10, 11, 12)
              );

When I call $multiArray['key1'], I get the value (which is normal):

// Example 1
$multiArray['key1'];
//$multiArray only has [1, 2, 3, 4]

Is there a way that when I call I want $multiArray['key1'] that I can have ['key1' => array(1,2,3,4)] or the other two keys, depending on the situation?

I could structure $multiArray like so, but I was wondering if there is a better way.

// Example 2
$multiArray = array(
                 'keyA' => array('key1' => array(1, 2, 3, 4)),  
                 'keyB' => array('key2' => array(5, 6, 7, 8)),
                 'keyC' => array('key3' => array(9, 10, 11, 12))
              );
$multiArray['keyA'];
// $multiArray is now what I want: ['key1' => [1, 2, 3, 4]]
2
  • 1
    Could you point out why you would need the key if you already access the array using a key? You may retrieve all array keys using $arrKeys= array_keys($multiArray);, does that help? Commented Nov 27, 2013 at 16:25
  • I think bcmcfc's answer about the getArray() function might be what I was looking for. I just wasn't thinking clearly about what I wanted. Commented Nov 27, 2013 at 16:53

2 Answers 2

1

You could do something like this:

function getArray ($multiArray, $key) {
    return array($key => $multiArray[$key]);
}

or

$result = array('key1' => $multiArray['key1']);

A little more context as to how you're using it would be useful though. It sounds like you already know the requested key at the point of use. If not you may need to use array_keys.

Sign up to request clarification or add additional context in comments.

1 Comment

I am trying to pass this variable to a function that I do not control, and it expects the data structure I was asking about. I think your utility function is what I was looking for.
1

I think what you may be looking for is foreach:

$myArray = array('key1' => array(1, 2, 3), 'key2' => array(4, 5, 6));
$multiArray = array();
foreach ($myArray as $key => $value) {
    // $key would be key1 or key2
    // $value would be array(1, 2, 3) or array(4, 5, 6)
    $multiArray[] = array($key => $value);
}

1 Comment

I'm not looking to take apart the array. I need to restructure it.

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.