代码之家  ›  专栏  ›  技术社区  ›  Gislef

Foreach URL JSON解码

  •  1
  • Gislef  · 技术社区  · 8 年前

    $urlsDB 是包含JSON的变量。

    print_r($urlsDB );
    

    [\"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/LOGO-SEG-2.png\",\"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/algoritims.jpg\"]
    

    如何创建 foreach 使用 json_decode 正确地

       <?php
        $urls = json_decode($urlsDB , true);
    
        if ($urls != '' ) { 
    
                foreach ($urls as $url) {
        ?>
        <img src="<?php echo $url;?>"  class="img-responsive img-thumbnail " />
    
        <?php
         }
        }
    
        ?>
    

    Var_dump($urls);

    2 回复  |  直到 8 年前
        1
  •  1
  •   ishegg    8 年前

    您得到的JSON无效。您在开头和结尾转义了引号。这是有效的:

    ["http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/LOGO-SEG-2.png","http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/algoritims.jpg"]
    

    这应该是可行的:

    <?php
    $a = '["http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/LOGO-SEG-2.png","http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/algoritims.jpg"]
    ';
    $urls = json_decode($a, true);
    if (count($urls) > 0) {
        foreach ($urls as $url) {
        ?>
            <img src="<?php echo $url;?>"  class="img-responsive img-thumbnail " />
        <?php
        }
    }
    

    你不应该 htmlspecialchars() JSON编码的字符串。这将转义引号,使JSON对象无效。你应该做的是 htmlspecialchars() here ).

        2
  •  0
  •   William Perron    8 年前

    json_decode()

    $input = '[\"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/LOGO-SEG-2.png\",\"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/algoritims.jpg\"]';
    
    $json = json_decode(stripslashes($input),true);
    

    的输出 var_dump($json)

    array(2) {
        [0]=> string(64) "http://localhost/theme/wp-content/uploads/2017/08/LOGO-SEG-2.png"
        [1]=> string(64) "http://localhost/theme/wp-content/uploads/2017/08/algoritims.jpg"
    }
    

    试试看 here


    编辑以添加:

    原始字符串实际上是json数组的字符串表示,而不是对象,因为它没有键。我用一个 url

    $input = '[{\"url\" : \"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/LOGO-SEG-2.png\"},{\"url\" : \"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/algoritims.jpg\"}]';
    
    $json = json_decode(stripslashes($input),true);
    

    array(2) {
        [0]=> array(1) {
            ["url"]=> string(64) "http://localhost/theme/wp-content/uploads/2017/08/LOGO-SEG-2.png"
        }
        [1]=> array(1) {
            ["url"]=> string(64) "http://localhost/theme/wp-content/uploads/2017/08/algoritims.jpg"
        }
    }
    

    \" " $encoded = "{\"some value\"}"; ).

    echo var_dump(json_decode('{\"myKey\": \"myValue\"}', true)); // output: NULL
    

    试试看 live .