0

I'm using json_encode() to pass data. This is my foreach loop.

foreach ($result as $val) {
    $data[] = array('item'=>$val["item"]);
    $data[] = array('availability'=>$val["stocks"]););
}

the output is

[
    {
        "item": "Anchor Butter"
    },
    {
        "availability": "no"
    },
    {
        "item": "Kraft Chedder"
    },
    {
        "availability": "yes"
    }
]

My question is how can I do the output as below?

[
    {
        "item": "Anchor Butter",
        "availability": "no"
    },
    {
        "item": "Kraft Chedder",
        "availability": "yes"
    }
]

2 Answers 2

4

You are adding 2 elements to the $data array in each iteration. Instead, try this:

foreach ($result as $val){
    $data[] = array('item'=>$val["item"], 'availability'=>$val["stocks"]));
}
Sign up to request clarification or add additional context in comments.

Comments

2
$info=array();
while ($row = mysql_fetch_assoc($result)) {
    $info1= array();
    $info1["item"]=$row["item"];
    $info1["availability"]=$row["stocks"];
    array_push($info, $info1);  
}
print_r($info); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.