如何使用array()在PHP中声明关联数组?

问题描述:

这是给PHP的警告如何使用array()在PHP中声明关联数组?

<?php 
$xml = simplexml_load_file("videos.xml") or die("Error: Object creation 
Failed"); 
$videos = array(); 

foreach($xml->children() as $video){ 
    $a= $video->Serial; 
    $b=$video->URI; 
    $videos[$a] = $b; 
} 

header('Content-type: application/json'); 
echo json_encode($videos); 
?> 

非法偏移类型在第8行如何解决呢?

+3

http://php.net/manual/fr/function.array.php – Fky

+4

标记为非常低的质量。 – Adam

+1

'$ files = array();'然后'$ files ['key'] =“value”;' – nerdlyist

使用键为数组赋值。你可以简单的写:

$files = array(); 
$files['some_key'] = 'an important value'; 
$files['another_key'] = 'a value'; 
$files['key'] = 'an non-important value'; 

输出:

Array 
(
    [some_key] => an important value 
    [another_key] => a value 
    [key] => an non-important value 
) 

您也可以只是简单地陈述var[array_key'] = some_value'创建一个数组。

例如:

$another['key'] = "WOW... that's cool"; 

输出:

Array 
(
    [key] => WOW... that's cool 
) 

而且......享受...

真的PHP是阵列超宽松

这就是你会做:

$files = array(); 
$files['key'] = "value"; 

然而,即使是这样的索引和关联的组合将工作:

<?php 

$files = array(); 

for($i=0; $i < 10; $i++){ 
    if($i%2 ==0){ 
     $files["Test".$i] = $i; 
    } else { 
     $files[]=$i; 
    } 
} 

echo "<pre>"; 
print_r($files); 

,输出:

Array 
(
    [Test0] => 0 
    [0] => 1 
    [Test2] => 2 
    [1] => 3 
    [Test4] => 4 
    [2] => 5 
    [Test6] => 6 
    [3] => 7 
    [Test8] => 8 
    [4] => 9 
)