2

I'm trying to create a JSON array with loop, I stored languages name in database and retrieving from query, after that I need to convert it into this format

$arrayName = array('lang-1' => null , 'lang-2' => null, ..... ,'lang-n' => null );

how can I achieve that

PHP code is like this

include_once "inc/init.php";
header('Content-Type: application/json');
$arrayName = array();
$query = $db->query("SELECT * FROM `medium`");
while ($data = mysqli_fetch_assoc($query)) {
array_push($arrayName, $data['medium']);
}
echo json_encode($arrayName);

im getting in this format

[
 "Kannada",
 "Telugu",
 "Tamil",
 "Urdu",
 "Spanish",
 "Arabian"
]

im trying pushing value but im not getting in that format, please help me

Thank you

4
  • 2
    And what format do you get? How does your table structure looks like? Commented Mar 18, 2017 at 18:21
  • 1
    I need to see your table structure to write you an answer for your issue. Commented Mar 18, 2017 at 18:29
  • database table? it is having only 2 columns. id and language columns Commented Mar 18, 2017 at 18:30
  • i need language name as key n value is null Commented Mar 18, 2017 at 18:30

2 Answers 2

2

Based on your comments I'm asuming that $data['language'] represents a name of your language. Then you can achieve your goal by the following code:

include_once "inc/init.php";
header('Content-Type: application/json');
$arrayName = array();
$query = $db->query("SELECT * FROM `medium`");

while ($data = mysqli_fetch_assoc($query)) {
    $arrayName[$data['language']] = null; // $array[$key] = $value
}

echo json_encode($arrayName);
Sign up to request clarification or add additional context in comments.

1 Comment

yes, thank you, in this format only i wanted that array,
1

using array_push you will get the same result

include_once "inc/init.php";
header('Content-Type: application/json');
$arrayName = array();
$query = $conn->query("SELECT * FROM `medium`");
while ($data = mysqli_fetch_assoc($query)) {
array_push($arrayName,$data['language ']);

}
$arrayName=array_fill_keys($arrayName, 'null'); 
echo json_encode($arrayName);

5 Comments

in this case i'll get all languages in different array object, like [{lang-1}, {lang-2}....{lang-n}] this
above answer is solved my question, anyway thank you for replay
@Rak_code right! please see now it will work for you
Yeah. It is also working fine. :) tq tq for your answer
it's my pleasure!

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.