How to 'JSON_Encode()' Keys from PHP Array

How do I `json_encode()` keys from PHP array?

You can force that json_encode uses an object although you’re passing an array with numeric keys by setting the JSON_FORCE_OBJECT option:

json_encode($thearray, JSON_FORCE_OBJECT)

Then the returned value will be a JSON object with numeric keys:

{"0":1691864,"1":7944458,"2":9274078,"3":1062072,"4":8625335,"5":8255371,"6":5476104,"7":6145446,"8":7525604,"9":5947143}

But you should only do this if an object is really required.

How to json_encode php array but the keys without quotes

First, you have to generate your array in php so the data's value are integers, not strings:

I emulated your array from your json_encode(), I guess it looks like this (or it should):

$array =  array(
array("label" => "Crear Usuario", "data" => 2),
array("label" => "Impresoras", "data" => 1),
array("label" => "Problema Correo", "data" => 1),
array("label" => "Requisicion Equipo", "data" => 1),
array("label" => "Sitio Web", "data" => 1)
);

$data = json_encode($array);
  • Notice that the 2 and 1's are unquoted, so this way they are integers, this is important.

Then you are missin in Javascript the JSON.parse() to actually make that output into a json object:

<script>
var data = '<?php echo $data; ?>';
var json = JSON.parse(data);
console.log(json);
console.log(json[0]);
</script>
  • Notice that var data = ... is SINGLE QUOTED, so you catch the echo from php as a String

The console.log()'s output this for me:

[Object, Object, Object, Object, Object] // First console.log(): one object with the 5 Objects. 
Object {label: "Crear Usuario", data: 2} // secons console log (json[0]) with the first object

Looks like what you need, am I right?

Custom keys in json_encode array

Your code works! The issue is in $list array you need define all keys in $result otherwise you need to check if there is that key in $list array.

$result =array(
'instock' => 'yes',
'item' => 'ch00024',
'color' => 'blue',
'price' => 100
);

$main = array();

$list = array('instock' => 'output1', 'item' => 'output2');

foreach ($result as $key => $value){
if (!empty($list[$key])) {
$main[$list[$key]] = $value;
}
}
echo json_encode($main);

Edit

Because you are access 2 dimensional array, so you need an extra loop to go through all items

$result = array(
array (
'instock' => 'yes',
'item' => 'it0215'
),
array(
'instock' => 'yes',
'item' => 'it0381'
)
);

$main = array();

$list = array('instock' => 'output1', 'item' => 'output2');

foreach ($result as $item){
foreach ($item as $key => $value) {
$main[$list[$key]] = $value;
}
}

echo json_encode($main);

The output is

{"output1":"yes","output2":"it0381"}

But In case you want to get all items with key replacement in new array. You should do something like this:

foreach ($result as $index => $item){ 
foreach ($item as $key => $value) {
$main[$index][$list[$key]] = $value;
}
}

echo json_encode($main);

The output is:

[
{"output1":"yes","output2":"it0215"},
{"output1":"yes","output2":"it0381"}
]

How to json encode Specific Key value using PHP?

I have solved..

$queryfetch = 'select * from table';

$result = mysqli_query($connection, $queryfetch);

$row = mysqli_fetch_assoc($result);

$data[] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name']
);

echo json_encode($data);

This code is working very well..

How can I access my nested array key in codeignigter?

for ($i=0; $i < sizeof($value->albumimages); $i++) {
$x = count($value->albumimages);
switch($x) {
default:
if($i == 0 || $i == 1)
{
echo '<div class="col-sm-6 pads5 marb10"> <img class="full" src="'.getapiPath().$value->albumimages[$i]->imagepath.'"> </div>';
}
break;
}
}

Ajax json_encode error: Uncaught SyntaxError: Unexpected token : when returning array with keys

jQuery's ajax function should automatically parse the response into an object. Just remove your eval statement and assign the response to your resultObj. Also, since you're not posting anything, it should probably be a "GET", which is defaulted. (Don't forget to change your php code too).

$.ajax({
url: "ajax_return_array.php",
success: function(result) {
if(result) {
resultObj = result;
alert( resultObj );
} else {
alert("error");
}
}
});

PHP json_encode() specific key of an array

I have read your question earlier and prepared the answer but you removed it before i paste the answer. Anyways here is the solution

function outer(&$val, $key) {
$val['time'] = json_encode($val['time']);
}
array_walk($your_array, 'outer');
print_r($your_array);

Encode PHP array with non-numeric keys to JSON array

You can use array_values:

echo json_encode(array_values($a));

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).



Related Topics



Leave a reply



Submit