tags:

views:

271

answers:

2

Using CakePHP (On PHP 5.2.6) I do a list query on a table which returns an array like:

Array (

[0] => None
[3] => Value 1
[5] => Value 2

)

Since it's not a sequential array json_encode() encodes it to an object instead of a JSON array which I need for filling a Jeditable Select.

PHP 5.2.6 does not support any additional parameters, so I can't force it to create an JSON encoded array.

My question, does anyone know how I can solve this problem in a clean way?

+2  A: 

see http://docs.php.net/array_values :

array_values() returns all the values from the input array and indexes numerically the array.

e.g.

$a = array(
  0 => 'None',
  3 => 'Value 1',
  5 => 'Value 2'
);
$x = array_values($a);
print_r($x);
echo json_encode($x);

prints

Array
(
    [0] => None
    [1] => Value 1
    [2] => Value 2
)
["None","Value 1","Value 2"]

edit: Javascript arrays can't have gaps. You'd have to fill the missing elements with e.g. NULL.

$a = array(
  0 => 'None',
  3 => 'Value 1',
  5 => 'Value 2'
);

$na = array_pad(array(), max(array_keys($a)), null);
$a += $na;
ksort($a);
echo json_encode($a);

prints ["None",null,null,"Value 1",null,"Value 2"]

VolkerK
Thank you so much for the extensive answer, however I must preserve the index, I forgot to add that part.So if an user selects something the numeric value(ID) is posted and the Value1 and Value2 would be displayed. My apologies for not making that really clear!
JanWillem
You can do that with an js object, too. Is there another reason why you _need_ an array?
VolkerK
Thank you VolkerK, this saved my day, I didn't fill it with nulls, but played with the sorting and it did the trick ;)
JanWillem
+2  A: 

If you want to preserve the indexes, you need to use an object. If not, pass it through array_merge to reindex the array.

www.php.net/array_merge

voidstate
Thank you for your answer, however I need it to be an array, and need to preserve the index...
JanWillem
An object in JSON *is* an array with non-sequential keys. From json.org: * A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. * An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
voidstate