4

I trying to figure out how to output my php to echo for my json file.

<?php
$sql_query = "SELECT * FROM some_data";
$result = mysql_query($sql_query);
$total_rows = mysql_num_rows($result);
$dataList_desc = '';
$dataList_view = '';
    while($row = mysql_fetch_array($result)) {
            $video_desc = $row["video_desc"];
            $video_views = $row["video_views"];
            $dataList_desc .= '' . $video_desc . '';
            $dataList_view .= '' . $video_views . '';
            echo "[[\" \", \"" . $dataList_desc . "\",],[\" \", \"" . $dataList_view . "\",]";

    }
  mysql_close($con);
?>

My output is:

[[" ", "Title 1",],[" ", "1000",][[" ", "Title 1Title 2",],[" ", "1000906",][[" ", "Title 1Title 2Title 3",],[" ", "10009061150",][[" ", "Title 1Title 2Title 3Title 4",],[" ", "100090611501800",][[" ", "Title 1Title 2Title 3Title 4Title 5",],[" ", "100090611501800756",][[" ", "Title 1Title 2Title 3Title 4Title 5Title 6",],[" ", "100090611501800756558",]

What I need is:

[["", "Title 1", "Title 2", "Title 3", "Title 4", "Title 5", "Title 6"],["", 1000, 903, 1150, 1800, 756, 558]]

Please help.

2 Answers 2

12
$desc = array(); $views = array();
while($row = mysql_fetch_array($result)) {
        $desc[] = $row["video_desc"]; // or smth like $row["video_title"] for title
        $views[] = $row["video_views"];
}
$res = array($desc, $views);
echo json_encode($res);
Sign up to request clarification or add additional context in comments.

1 Comment

So simple. Thank you so much, I spent the whole evening trying to figure out.
10

Don't create your own JSON! Use json_encode to encode an array.

$data = array();
while ($row = mysql_fetch_assoc($result)) {

    ... maybe some processing of $row here ...

    $data[] = $row;
}

echo json_encode($data);

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.