JSON - json_encode没有正确地形成foreach循环

时间:2015-08-23 18:42:22

标签: php json

这是我的PHP代码:

<?PHP


$url = 'http://www.sportsdirect.com/dunlop-mens-canvas-low-top-trainers-246046?colcode=24604622';
libxml_use_internal_errors(true); 
$doc = new DOMDocument();
$doc->loadHTMLFile($url);

$xpath = new DOMXpath($doc);

    $DataVariants = $xpath->query('//span[@class="ImgButWrap"]/@data-variants')->item(0)->nodeValue;

    $jsonStart = strpos($DataVariants, '[');
    $jsonEnd = strrpos($DataVariants, ']');

    $collections = json_decode(substr($DataVariants, $jsonStart, $jsonEnd - $jsonStart + 1));   


    $result = array();

    foreach ($collections as $item) {
        $ColVarId = $item->ColVarId;


        $SizeNames = [];
        foreach ($item->SizeVariants as $size) {
            $SizeNames[] = $size->SizeName;
        }

        if (in_array("7", $SizeNames)) {
            $result[]['colorids'] = $ColVarId;              
        }

    }

    echo json_encode($result);  


?>

Echo打印出这个:

[{"colorids":"24604603"},{"colorids":"24604684"},{"colorids":"24604640"},{"colorids":"24604609"},{"colorids":"24604682"},{"colorids":"24604686"},{"colorids":"24604681"},{"colorids":"24604689"},{"colorids":"24604602"},{"colorids":"24604679"},{"colorids":"24604680"},{"colorids":"24604622"},{"colorids":"24604685"},{"colorids":"24604683"},{"colorids":"24604621"},{"colorids":"24604677"},{"colorids":"24604688"}]

所需的输出格式为

{"colorids": ["id1","id2","id3","id4","id5","id6","id7","id8"] }

几小时后我无法理解我的错误在哪里。你能帮我解决这个问题,因为我认为回声结果不正确。

提前致谢!

3 个答案:

答案 0 :(得分:2)

您的代码会创建一个数组数组

if (in_array("7", $SizeNames)) {
   $result[]['colorids'] = $ColVarId;              
}

to,

if (in_array("7", $SizeNames)) {
        $result['colorids'][] = $ColVarId;              
}

输出

{"colorids":["id1","id2","id3","id4","id5","id6","id7","id8"]}

答案 1 :(得分:1)

$result[]['colorids']

从json_encode的角度来看,您正在向数组中添加一个具有属性colorids的新对象。但是你想要一个具有属性colorids的对象是一个字符串数组(或多或少反过来):

$result = array( 'colorids'=>array() );
...
$result['colorids'][] = $ColVarId;

答案 2 :(得分:1)

使用此:

if (in_array("7", $SizeNames)) {
        $result['colorids'][] = $ColVarId;              
}

获得此类输出

{"colorids":["id1","id2","id3","id4","id5","id6","id7","id8"]}