PHP Array to Json Array Using Json_Encode();

PHP Array to JSON Array using json_encode();

If the array keys in your PHP array are not consecutive numbers, json_encode() must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.

Use array_values() on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering:

Example:

// Non-consecutive 3number keys are OK for PHP
// but not for a JavaScript array
$array = array(
2 => array("Afghanistan", 32, 13),
4 => array("Albania", 32, 12)
);

// array_values() removes the original keys and replaces
// with plain consecutive numbers
$out = array_values($array);
json_encode($out);
// [["Afghanistan", 32, 13], ["Albania", 32, 12]]

json_encode PHP array as JSON array not JSON object

See Arrays in RFC 8259 The JavaScript Object Notation (JSON) Data Interchange Format:

An array structure is represented as square brackets surrounding zero
or more values (or elements). Elements are separated by commas.

array = begin-array [ value *( value-separator value ) ] end-array

You are observing this behaviour because your array is not sequential - it has keys 0 and 2, but doesn't have 1 as a key.

Just having numeric indexes isn't enough. json_encode will only encode your PHP array as a JSON array if your PHP array is sequential - that is, if its keys are 0, 1, 2, 3, ...

You can reindex your array sequentially using the array_values function to get the behaviour you want. For example, the code below works successfully in your use case:

echo json_encode(array_values($input)).

PHP array not converting to JSON using json_encode

If json_last_error gives you the JSON_ERROR_UTF8 error code (5), then you will have to encode your datas in UTF-8 :

Need to convert final array to utf-8.

<?php

$response = array_map('utf8_encode', $response);

Passing a php array as a json element with json_encode in a hidden input

Proper code is

echo "<input id='json_pics' type='hidden' value='" . json_encode($pic_array) . "'/>";

In your current code php doesn't understand that you try to use json_encode function and just sees $pic_array variable which is array.

PHP json_encode , force the creation of an array even if it has only one element

If this is the structure of the entire XML and not just a fragment from something bigger, you can turn it into an array or a mix of arrays and objects using less code:

$xml = simplexml_load_string($getPostData);

$array = array('item' => array());
foreach ($xml->item as $item) {
$array['item'][] = (object)(array)$item;
}

echo(json_encode($array));

This will produce the output you described in the question as expected, no matter how many <item> elements appear in the XML.

Remove the (object) from the code inside the foreach() to get the <item> elements converted to arrays instead of stdClass objects.

PHP Array to Json Object

You want to json_encode($json, JSON_FORCE_OBJECT).

The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.

You can also eliminate the use of array_push for some slightly cleaner code:

$json[] = ['ip' => $ip, 'port' => $port];

php json_encode the same key as array

To get valid JSON with what you currently have you need to do this:

header('Access-Control-Allow-Origin: *');
header("Cache-Control: no-cache");
header('Content-Type: application/json');
include("dbcon.php");
$sql = "SELECT * FROM quiz;";
$result = $conn->query($sql);
$theResultIWant = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$theResultIWant[] = $row;
}
}
else {
echo "nodata";
}
$conn->close();
echo json_encode($theResultIWant, JSON_PRETTY_PRINT);
//That is all

To get the result you want to get:

header('Access-Control-Allow-Origin: *');
header("Cache-Control: no-cache");
header('Content-Type: application/json');
include("dbcon.php");
$sql = "SELECT * FROM quiz;";
$result = $conn->query($sql);
$theResultIWant = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
foreach ($row as $key=>$value) {
$theResultIWant[$key] = $theResultIWant[$key]??[]; //or isset($theResultIWant[$key])?$theResultIWant[$key]:[]; in PHP < 7
$theResultIWant[$key][] = $value;
}
}
}
else {
echo "nodata";
}
$conn->close();
echo json_encode($theResultIWant, JSON_PRETTY_PRINT);

Either approach is reasonable to read JavaScript with, but the second one is said to be more compact in terms of size (however the first one can be compressed more if you're GZipping the result).

How to convert this associative array into this json output using json_encode()

<?php
// original array
$a = array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
);
// transform
$b = array();
foreach($a as $key=>$value) {
$b[] = array('Location_name'=>$key, 'Link_name'=>$value);
}

// output
echo json_encode($b);

?>

Result:

[{"Location_name":"Location_1","Link_name":"Link_1"},{"Location_name":"Location_2","Link_name":"Link_2"}]


Related Topics



Leave a reply



Submit