【问题标题】:How to declare an associative array in PHP using array()? [closed]如何在 PHP 中使用 array() 声明关联数组? [关闭]
【发布时间】:2018-03-31 17:21:09
【问题描述】:

这是给 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 行中的非法偏移类型。如何修复它?

【问题讨论】:

  • 被标记为质量非常低。
  • $files = array(); 然后$files['key'] = "value";
  • @Fky 为什么是法语?
  • 是的,你写的是@Piyin。它是 SimpleXMLElement 对象类型。我已经将它转换为字符串。它现在完美无缺:)。谢谢

标签: php xml-parsing


【解决方案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
)

然后……享受……

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 1970-01-01
      • 2021-03-05
      • 2012-10-11
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      相关资源
      最近更新 更多