1

This is related to Need to display only array value in JSON output asked earlier.

I just want to show only values like

[
"autoComplete",
"ColdFusion",
"jQuery Mobile"
];

Background: I am using and AJAX call via Jquery mobile to retrieve data from server (language:PHP). I want to use https://github.com/commadelimited/autoComplete.js in my Phonegap Application.

Please advice! I am new to JSON.

3
  • 1
    Your question is extremely unclear. What have you tried? What are you having trouble with? Commented Feb 27, 2013 at 17:16
  • 1
    echo json_encode(array('autoComplete', 'ColdFusion', 'jquery Mobile')) does exactly what you want. Commented Feb 27, 2013 at 17:28
  • The values are generated dynamically from the database so could not do json_encode(array('autoComplete', 'ColdFusion', 'jquery Mobile')) Just posted my answer which is working (After working on it for hours!!). Commented Feb 27, 2013 at 17:44

2 Answers 2

2

when using json_encode, any array that has a zero based numeric index (meaning it is not an associative array and starts with 0 and is not missing any numbers) will be converted to a javascript array instead of a js object literal. You can use array_values in php to get all the values from an array numerically indexed.

<?php
//a generic array
$a = array(
    'foo'=>'bar',
    'one'=>'two',
    'three'=>'four');

//display the array in php
var_dump($a);
echo '<br>';

//json encode it
$json = json_encode($a);
var_dump($json);
echo '<br>';

//json encode just the values
$json = json_encode(array_values($a));
var_dump($json);

http://codepad.viper-7.com/hv06zn

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

Comments

0

Thanks Jonathan.

However I found the solution as below. I hope that it is useful to someone else too.

$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();

while($row = mysql_fetch_assoc($result)) {
  $records[] = $row["title"];
}


mysql_close($con);
echo json_encode($records);

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.