0

SQL output use for loop on the array , get only data to the new array and one key name ,data=> mycode:

$sql = "SELECT * FROM Alldata";
if($result = mysqli_query($mysqli,$sql))
{
    $rows = array();
    $newdata = array();
    while($row = mysqli_fetch_assoc($result))
    {
        $rows[] = $row;
    }
}
for($i = 0; $i <= 6; $i++){
    $newdata['data'][$i] = $rows[$i]['poo'];
}
echo json_encode($newdata);

output:

Array
(
    [data] => Array
        (
            [0] => 123
            [1] => 456
            [2] => 789
            [3] => 111
            [4] => 222
            [5] => 333
        )

)
{"data":["123","456","789","111","222","333"]}

but I want is like:

Array
(
    [0] => Array
        (
           
            [data] => 123,456,789,111,222,333
        )
)
[{"data":"123,444,555,666,777"}]

How to get this output? thank you!!

2
  • 2
    Why do you want the data in this form? Seems backwards. Commented Oct 1, 2020 at 11:42
  • implode(',', $yourArray) Commented Oct 1, 2020 at 11:46

2 Answers 2

1

I am not sure why you want the data as a comma-separated string but if you want to do something like this then you can simply implode() a single column from the result set. To get the column use array_column()

Change your code to this:

$sql = "SELECT * FROM Alldata";
$result = $mysqli->query($sql);
$rows = $result->fetch_all(MYSQLI_ASSOC);
$newdata[] = [
    'data' => implode(',', array_column($rows, 'poo'))
];
echo json_encode($newdata);

It produces this output:

[{"data":"1,2,3,6,7,8,9,10,11,12"}]

Sign up to request clarification or add additional context in comments.

2 Comments

Array ( [0] => Array ( [data] => 123,456,789,111,222,333 ) [1] => Array ( [data] => 456,666,777,888,333) )how to do it?
Do you mean split into groups of 6 elements each? Use array_chunk()
0

This will do the trick, simple use implode function.

$sql = "SELECT * FROM Alldata";
if($result = mysqli_query($mysqli,$sql))
{
    $rows = array();
    $newdata = array();
    while($row = mysqli_fetch_assoc($result))
    {
        $rows[] = $row;
    }
}
for($i = 0; $i <= 6; $i++){
    $newdata['data'][$i] = $rows[$i]['poo'];
}
$glue = implode(",",$newdata['data']);
$newdata['data'] = $glue;
echo json_encode($newdata);

3 Comments

Why not just get the value directly in your while-loop instead of adding an extra foreach?
If I need add array ...like this
Array ( [0] => Array ( [data] => 123,456,789,111,222,333 ) [1] => Array ( [data] => 456,666,777,888,333) ) )how to do it?

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.