Removing array index reference when using json_encode()
Use array_values()
for your issue:
$arr['dates'] = array_values($arr['dates']);
//..
$arr = json_encode($arr);
Why? Because you're unsetting array's key without re-ordering it. So after this the only way to keep that in JSON will be encode keys too. After applying array_values()
, however, you'll get ordered keys (starting from 0
) which can be encoded properly without including keys.
how remove the array object index in json_encode using php?
Why casting into object
? If you just remove the (object)
casting it will be done!
$obj['markers']=array( $arr1, $arr2 );
result:
{"markers":[{"latitude":9.9252007,"longitude":78.1197754,"title":"Madurai"},{"latitude":9.2323,"longitude":78.23233,"title":"Peraiyur"}]}
How to remove an item arrays as JSON objects in PHP
As order of keys in your array has changed after removing a certian key, json_encode
tries to save this new order. So, you need to reindex your array keys.
For this use array_values
, which
indexes the array numerically
$json = [/* your array here */];
unset($json[2]);
echo json_encode(array_values($json));
How to remove array index from json object while convert array to jsonobject php?
First of all, I need to change your code to this to even get the result you're talking about:
$arr = array('id' => $_POST['id'], 'name' => $_POST['name'], 'model' => $_POST['model'], 'color' => $_POST['color']);
$result = json_encode(array('success' => 1, 'message' => "Updated Successfully", $arr));
echo $result;
The problem you are facing with the key "0" is that you cannot have a value in JSON without a key (as other have stated in the comments). Notice that you set the key success
and message
, but you don't set a key for $arr
.
I think you should add a key data
or something similar to it like this:
$arr = array('id' => $_POST['id'], 'name' => $_POST['name'], 'model' => $_POST['model'], 'color' => $_POST['color']);
$result = json_encode(array('success' => 1, 'message' => "Updated Successfully", 'data' => $arr));
echo $result;
json_encode returns column name and array index
Use array_filter with ARRAY_FILTER_USE_KEY
flag
$keys = ["col1", "col2", "col3"];
foreach ($query as $row) {
$filtered = array_filter((Array) $row, function($key) use($keys) {
return in_array($key, $keys);
}, ARRAY_FILTER_USE_KEY);
$test = json_encode($filtered);
}
Notice: If your $row
is array not object you don't need to cast it to array (Array) $row
json with no index after unset encode array in php
I searched and tried anyway to implement the behaviour that i searched in my question but i didn't find nothing. I supposed that, like you can see in this answer, unset function adds indices to the array because the JSON_encode not support arrays with hole. So, to solve my problem, i load the JSON file with a jQuery function, delete the elements with jQuery and i call a ajax function to delete the files linked at the address contained in the json file:
$.getJSON('loadauto.json', function(result) {
var y = result;
$.each(result, function(i, field){
if(field.indirizzo_paginaauto == x){
delete result[i];
}
});
$.ajax({
async: true,
cache: false,
type: 'POST',
url: 'deleteauto.php',
data: { nuovofilejson: y, indirizzo: x},
success: function(data) {
alert ("Auto cancellata definitivamente");
},
error: function(data) {
alert ("Error");
}
});
}
PHP json_encode creates number index as string instead of an object
Because the array doesn't start with index 0
but with index 1
, it's encoded as an JSON object instead of an JSON array.
You can use the array_values()
function to remove the indexes and only keep the values.
Example:
$ret['testing'] = array_values($ret['testing'])
echo json_encode($ret);
But because you don't need the index at this moment, you can also refactor your code to this:
foreach($data as $index => $value){
if($index < 1){
$ret['test'][] = array(
'val' => $value,
'me' => 'index < 1'
);
}
else {
$ret['testing'][] = array(
'val' => $value,
'me' => 'index >= 1'
);
}
}
echo json_encode($ret);
This way, the arrays will always start with index 0
.
PHP json_encode as object after PHP array unset()
The reason for that is that your array has a hole in it: it has the indices 0 and 2, but misses 1. JSON can't encode arrays with holes because the array syntax has no support for indices.
You can encode array_values($a)
instead, which will return a reindexed array.
indexing JSON in php after removing item
$json = file_get_contents("data2.json");
$data = json_decode($json);
unset($data->nodes[$data_deleteNode]);
$data->nodes = array_values($data->nodes);
$json = json_encode($data);
file_put_contents("data2.json", $json)
$data->nodes
is the array you're modifying and that you need to reset. You do that with:
$data->nodes = array_values($data->nodes);
Note also that I renamed your variables so $json
refers to JSON encoded text, and $data
refers to decoded arrays/objects.
how to delete indexes on multidimensional arrays in php
Not sure quite what your question is here (please clarify by editing your post).
Your output does not look like a Php array. More like JSON.
When you say remove indexes, could this be from having non sequential 0 counted indexes?
See below:
<?php
$people =
[
[
'name'=>'fred',
'family'=>'flintstones'
],
[
'name'=>'barney',
'family' => 'rubble'
],
[
'name'=> 'wilma',
'family' => 'flintstones'
]
];
var_dump(json_encode($people));
unset($people[1]);
var_dump(json_encode($people));
var_dump(json_encode(array_values($people)));
Output:
string(116) "[{"name":"fred","family":"flintstones"},{"name":"barney","family":"rubble"},{"name":"wilma","family":"flintstones"}]"
string(88) "{"0":{"name":"fred","family":"flintstones"},"2":{"name":"wilma","family":"flintstones"}}"
string(80) "[{"name":"fred","family":"flintstones"},{"name":"wilma","family":"flintstones"}]"
You can use array_values to reindex arrays before encoding to JSON to 'remove' those indexes, and turn into a list of objects.
Related Topics
Add Columns to Admin Orders List in Woocommerce
New Lines (\R\N) Are Not Working in Email Body
Nested Array. Third Level Is Disappearing
Can't Pass MySQLi Connection in Session in PHP
Fatal Error: Using $This When Not in Object Context
MySQL No Connection Could Be Made Because the Target MAChine Actively Refused It
Hide Shipping Methods for Specific Shipping Class in Woocommerce
How to Concatenate Multiple Ternary Operator in PHP
Print Time in 15-Minute Increments Between Two Times in the Same Day
PHP - Regex to Allow Letters and Numbers Only
Requires Ext-Fileinfo. How to Add That into My Composer.JSON File
Checking If Array Is Multidimensional or Not
Check If String Contains a Value in Array