PHP:如何从关联数组中获取键和值?

时间:2013-11-27 16:22:20

标签: php

我有这种关联数组结构:

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

当我调用$ multiArray ['key1']时,我得到了值(这是正常的):

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

当我打电话时,我想要$ multiArray ['key1']我可以拥有['key1' => array(1,2,3,4)]或其他两个键,这取决于具体情况吗?

我可以像这样构造$ multiArray,但我想知道是否有更好的方法。

// 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 个答案:

答案 0 :(得分:1)

我认为您可能正在寻找的是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 :(得分:1)

你可以这样做:

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

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

关于你如何使用它的更多背景将是有用的。听起来你已经知道了使用点的请求密钥。如果不是,您可能需要使用array_keys