0

please tell me how to fetch data from MySql database in below format.

Now, i am getting data in below format

$sql="SELECT c.ad_id FROM `category_rel` c INNER JOIN tbl_category_master d ON c.category_id= d.fld_category_id WHERE d.fld_category_name IN ($category)";
$result1=$con->query($sql);
while ($row = mysqli_fetch_assoc($result1)) {
    $output[] = $row;
       }
$ids=json_encode(array($output));

Result:
[[{"ad_id":"2"},{"ad_id":"11"},{"ad_id":"28"},{"ad_id":"62"},{"ad_id":"64"}]]

But, I want in the below format:

["2","11","28","62"]

it should not come with the column name.

2 Answers 2

2

Try $output[] = $row['ad_id']; instead of $output[] = $row;

[Edit] Also remove array() function :

$sql="SELECT c.ad_id FROM `category_rel` c INNER JOIN tbl_category_master d ON c.category_id= d.fld_category_id WHERE d.fld_category_name IN ($category)";
$result1=$con->query($sql);
while ($row = mysqli_fetch_assoc($result1)) {
    $output[] = $row['ad_id'];
       }
$ids=json_encode($output);

Regards.

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

4 Comments

She faced the data as assoc.
I update the post as I don't see you use mysql_fetch_assoc, have you try ?
Sir, this is not implode. It show invalid argument. @Jean-Luc B.
Can you explain ? Does ad_id can be null ? result empty ? In this case add $output = array(), before while loop, it's good practice to init your vars even if php is permissive.
0

If you want to do it from while loop then use it:

$sql="SELECT c.ad_id FROM `category_rel` c INNER JOIN tbl_category_master d ON c.category_id= d.fld_category_id WHERE d.fld_category_name IN ($category)";
while ($row = mysqli_fetch_assoc($result1)) {
    $output[] = $row['ad_id']; //may be this will help Not sure the structure
}
$ids = json_encode(array($output));

If you need it from the output array then just use this:

$json = '[[{"ad_id":"2"},{"ad_id":"11"},{"ad_id":"28"},{"ad_id":"62"},{"ad_id":"64"}]]';

$arr = json_decode($json, true);


$arr = array_column($arr[0], 'ad_id');

echo '<pre>';
print_r($arr); 

Result:

Array
(
    [0] => 2
    [1] => 11
    [2] => 28
    [3] => 62
    [4] => 64
)

2 Comments

Its works but not me ..I want in ['2', '11', '28', '62','64'] this format ... Because i need to use these values in next SQl Statement under IN clause.
so you can use the implode function. As you already accept other answer so best of luck.

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.