2017-10-19 131 views
-7

這是給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

回答

1

使用鍵爲數組賦值。你可以簡單的寫:

$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 
) 

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

1

真的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 
)