Venelin
Venelin

Reputation: 3308

JSON - json_encode not formating properly foreach loop

Here is my PHP code:

<?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 prints this:

[{"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"}]

The desired output format is

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

In hours i can not understand where is my mistake. Can you help me out resolve this because i think the echo result is not correct one.

Thanks in advance!

Upvotes: 0

Views: 46

Answers (3)

Happy Coding
Happy Coding

Reputation: 2525

Use this :

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

to get the such output

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

Upvotes: 1

mdamia
mdamia

Reputation: 4557

your code creates an array of arrays

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

to,

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

output

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

Upvotes: 2

VolkerK
VolkerK

Reputation: 96159

$result[]['colorids']

From json_encode's point of view here you are adding a new object that has the property colorids to an array. But you want one object that has a property colorids that is an array of strings (more or less the other way round):

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

Upvotes: 1

Related Questions