如何创建一个关联数组,其中包含数组中的元素作为键,并使用数组作为相应的值?

时间:2014-01-18 17:25:05

标签: php arrays

我有数组$ devices,$ port

print_r($devices);
Array(
[0] => cisco1
[1] => cisco2
 )

print_r($port);
Array
(
[0] => Port1/1/1
[1] => Port1/1/10
[2] => Port1/1/11
) 

我想创建一个数组$ devlist,它将是这样的:

Array(

[cisco1] =>Port1/1/1
           Port1/1/10
           Port1/1/11

[cisco2] =>Port2/1/1
           Port2/1/10
           Port2/1/11

)

我的观点是每个设备中都有一系列设备($ devices)和端口阵列。 为$ device数组中的每个设备新创建 $ port 数组。

到目前为止我尝试了什么:

foreach ($devices as $value)
{
$port=();
//iam polling the respective device and getting a list of ports available for that device in array **$port**

array_push($devices[$value], $port);
}

此方法生成错误“array_push()期望参数1为数组,null为”

请原谅我,如果这似乎是一个简单的问题becoz我刚接触php和脚本:(

4 个答案:

答案 0 :(得分:1)

你想要这样的东西吗?如果是这样,我不明白为什么,当你可以使用每个$ device的$ ports值时?

$devices = array
(
    'cisco1', 'cisco2'
);

$ports = array 
(
    'Port1/1/1',
    'Port1/1/10',
    'Port1/1/11'
);

$dev_list = array();

foreach ($devices as $device) 
{
    $dev_list[$device] = array();

    foreach ($ports as $port) 
    {
        array_push($dev_list[$device], $port);
    }
}

echo '<pre>';
print_r($dev_list);
echo '</pre>';

Array
(
    [cisco1] => Array
        (
            [0] => Port1/1/1
            [1] => Port1/1/10
            [2] => Port1/1/11
        )

    [cisco2] => Array
        (
            [0] => Port1/1/1
            [1] => Port1/1/10
            [2] => Port1/1/11
        )

)

答案 1 :(得分:0)

您可以使用foreachfor循环,但主要的是您必须使用variable variables

解决方案一:

$devlist = array();
foreach($devices as $key => $device){
$devlist[$device] = ${"port".($key+1)};
}

解决方案二:

$devlist = array();
$size = sizeof($devices);
for($i = 0; $i < $size; $i++){
$devlist[$devices[$i]] = ${"port".($i+1)};
}

答案 2 :(得分:0)

如果我理解你的问题,你想要这样的事情:

$arr = array
(
    'cisco1' => array 
    (
        'Port1/1/1', 
        'Port1/1/10',
        'Port1/1/11'
    ),
    'cisco2' => array
    (
        'Port1/1/1', 
        'Port1/1/10',
        'Port1/1/11'
    )
);

foreach($arr as $key => $value) // use the foreach-loop like this to get both keys and values
{
    echo "$key: <br />-" . implode('<br />-', $value) . '<br /><br />';
}

打印:

cisco1: 
-Port1/1/1
-Port1/1/10
-Port1/1/11

cisco2: 
-Port1/1/1
-Port1/1/10
-Port1/1/11

答案 3 :(得分:0)

试试这个:

    $devlist = array();
    foreach ($devices as $value)
    {
            $port=();
            //iam polling the respective device and getting a list of ports available for that device in array **$port**

            $devlist[$value] = $port;
    }