in my d3js example contain [ symbol after children key & working perfectly
{"name": "root",
"children": [
{"name": "typeA(1095)",
"children": [
{"name": "2010(365)",
"children": [
{"name": "january(31)", "value": 31},
http://bl.ocks.org/mbostock/1283663
https://gist.github.com/mbostock/1283663/raw/a05a94858375bd0ae023f6950a2b13fac5127637/readme.json
but i convert a multi-dimensional array using php json_encode there is no [ symbol so when i pass it to d3js example it's not working
$json = array('name'=>'p_date','children'=>array('name'=>'HedCET','value'=>10));
json_encode($json) output
{"name":"p_date","children":{"name":"HedCET","value":10}}
there is no [ symbol after children key, is there any additional option to enable [ symbol in php json_encode ?
OR is there any difference between d3js json file and php json file ?
In PHP
'children' => array('name' => 'HedCET', 'value' => 10)
is
"children": {"name": "HedCET", "value": 10}
in JSON.
You have forgotten to put another array():
'children' => array( array('name' => 'HedCET', 'value' => 10) )
Related
I have two nested arrays with different length. I want to make length of second array as per first array, see below examples to get idea. Just remove all those items which don't exist in first array. Sometime second array has more values then first array, in this case my tree structure breaks.
These arrays are nested array so simple array_slice not working.
Here are the structure of array.
First Array
"1": {
"id": "1",
"username": "username",
"children": [
{
"id": "-1",
"username": "NULL",
"children": [
{
"id": "-1",
"username": "NULL",
"children": [
{
"id": "-1",
"username": "NULL",
"children": []
}
]
}
]
}
]
}
Second Array
"157": {
"id": "157",
"username": "test1",
"children": [
{
"id": "158",
"username": "test1",
"children": [
{
"id": "159",
"username": "test2",
"children": [
{
"id": "160",
"username": "test3",
"children": []
},
{
"id": "160",
"username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
"children": []
}
]
}
]
},
{
"id": "160",
"username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
"children": [
{
"id": "159",,
"username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
"children": [
{
"id": "161",
"username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
"children": []
}
]
}
]
}
]
}
Expected Output
"157": {
"id": "157",
"username": "test1",
"children": [
{
"id": "158",
"username": "test1",
"children": [
{
"id": "159",
"username": "test2",
"children": [
{
"id": "160",
"username": "test3",
"children": []
},
]
}
]
},
]
}
I am trying this method, but it is not working.
$firstCount = (array_map('count', $actualTree));
$secondCount = (array_map('count', $emptyTree));
$chunk = array_slice($actualTree, 0 , $second[$this->userId], true);
Use Case
The thing which I want to do is that remove those array childrens completely which are not exists in first array. I am building a binary tree upto three levels. First array already has a binary tree with empty values. The second array is data that is coming from the database, and I am simply replacing empty data with the actual data using array_replace. This is working good until second array has more values then first array. So to make it working I have to remove those extra elements.
Could anyone please help me to make there length same. Any help will be appreciated.
Thanks in advance.
A Stack Overflow miracle has occurred... I got a recursive snippet to work on the first pass! Usually it takes me a good hour or two to write something that works.
I don't know if I can make it any tighter/better OR if it will fail on any fringe cases, but:
it works for your sample input
it is midnight for me, I'm tired, and I have to work in the morning
Effectively, it synchronously & recursively iterates each array and stores each level of the entry array to the output array so long as the same level keys exists in the structure array.
Code: (Demo)
function truncateRecursive($structure, $entry) {
$output = [];
while (($structureKey = key($structure)) !== null && ($entryKey = key($entry)) !== null) {
$output[$entryKey] = !is_array($entry[$entryKey])
? $entry[$entryKey]
: truncateRecursive($structure[$structureKey], $entry[$entryKey]);
unset($structure[$structureKey], $entry[$entryKey]);
}
return $output;
}
var_export(truncateRecursive($structure, $entry));
Output:
array (
157 =>
array (
'id' => '157',
'username' => 'test1',
'children' =>
array (
0 =>
array (
'id' => '158',
'username' => 'test1',
'children' =>
array (
0 =>
array (
'id' => '159',
'username' => 'test2',
'children' =>
array (
0 =>
array (
'id' => '160',
'username' => 'test3',
'children' =>
array (
),
),
),
),
),
),
),
),
)
This question already has answers here:
Creating a jSON object using php loop
(2 answers)
Create a Json array in a for loop - php
(2 answers)
Closed 1 year ago.
How to add commas to a json print?
$result = curl($url);
$result = json_decode($result , true);
$resultdata = $result ['data'];
foreach($resultdata as $data){
$print= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
print json_encode($print);
}
this is the response from my code
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
}
{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
}
{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
I want to have a comma for each json result
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
},{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
},{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
What you actually need to do is produce an array of results, which you can do by pushing values into an array in the loop, and then json_encode the array after the loop:
$print = array();
foreach($resultdata as $data){
$print[]= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
}
print json_encode($print);
I don't get the point of having ',' but I'm guessing you want a valid json output. If so I guess that your result data is an array:
<?php
$result = [ 'data' => [
[
"id" => "17996292388215089",
"username" => "hanikfadhilah",
"text" => "Loh kapan ini huuu pengen"
],
[
"id" => "17877856039348099",
"username" => "titan_kdk",
"text" => "Mntb"
],
[
"id" => "17860767967398064",
"username" => "explorecentraljava",
"text" => "Terbaik fotonya lur"
]
]
];
so all what you need to do in order to get it as a valid json is:
print json_encode($result['data'], JSON_PRETTY_PRINT);
that produces output:
[
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
},
{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
},
{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
]
no need for any foreach loop.
json_encode()
I'm working with Elasticsearch-PHP client. I want to index my datas, but I have a problem with mapping. There is a problem: I create my data array, everything works fine, but when I add this array to my index body => my_data_array some datas show up, but not all of them. I don't know why. I just digged and try all of following steps but nothing changed.
I just attached my snippets.
This my controller file where I index datas:
{
$params = ['body' => []];
foreach($all_ads as $key => $ads){
$params['body'][] = [
'index' => [
'_index' => 'demo_data',
'_type' => 'demo',
'_id' => $ads->id
]
];
$params['body'][] = $ads->indexParams();
}
$responses = $client->bulk($params);
this is result json object:
"response": [
{
"id": 85345,
"old_id": "5088063",
"user_id": "2706",
"category_id": "15",
"type": "3",
"title": array[3],
"slug": "",
"sub_region_id": "8",
"condition": "1",
"username": "John Doe",
"price": "82000",
"price_type": "1",
"no_phone": "0",
"views": "29",
"hot": "0",
"vip": "0",
"price_measure": "0"
}
I have a datafield and it is not visible here.
Its data mapping structure
'data' => [
'type' => 'object',
'properties' => [
'key_id' => ['type' => 'integer'],
'value_id' => ['type' => 'integer'],
'key' => ['type' => 'keyword'],
'value' => ['type' => 'keyword']
]
]
How can I fix it?
I just check some question from here and github issue forum but nothing helps. Thanks!
You have to follow solution of the question. Its maybe helpful for you.
Elasticsearch mapping not working as expected
Ask Question
[{
"forms": [{
"id": "52b55960-023e-11e7-9140-f3c1d163524b",
"title": "Default Form",
"update_history": [{
"version": "1",
"updated_at": "2016-12-10 12:12:10"
}, {
"version": "2",
"updated_at": "2017-01-01 05:17:19"
}, {
"version": "3",
"updated_at": "2017-02-07 03:22:39"
}, {
"version": "4",
"updated_at": "2017-03-03 02:28:56"
}, {
"version": "5",
"updated_at": "2017-01-11 07:01:22"
}]
}]
}]
I have above Json stored in Dynamo-DB table. forms object is parent object. I have stored form updated detail version and updated_at in update_history nested object. I want updated_at of version of 2. Please suggest me, what is wrong in below query. I got empty result.
`$response = $client->scan([
'TableName' => 'TableName',
'ProjectionExpression' => 'Json.forms.update_history.updated_at',
'ExpressionAttributeValues' => [
':val1' => ['S' => '52b55960-023e-11e7-9140-f3c1d163524b'],
':val2' => ['S' => '2']
],
'FilterExpression' => 'id = :val1 and Json.forms.update_history.version = :val2',
]);`
Please refer the DocumentPath example in the below link and try to use deference operator.
For a nested attribute, you construct the document path using
dereference operators.
If you don't know the deference operator (i.e. index), you can't filter the data as you have tried.
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html#DocumentPaths
Example:-
Accessing List Elements:-
MyList[0]
AnotherList[12]
ThisList[5][11]
Accessing Map Elements:-
MyMap.nestedField
MyMap.nestedField.deeplyNestedField
You have the combination of both Map and List, you need to FilterExpression accordingly.
I've got a request to present the data in the following format as a JSON feed:
{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
However in my PHP code, I think I need to have a key itterator - but I end up with this format:
{
"0": {
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
"1": {
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
}
Any ideas on how to build the first data set with out having the index iterator?
simple create an array of objects, no need for the key (notice the [ ] surrounding your list)
json.txt
[{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}]
example.php
<?php
$data = json_decode(file_get_contents('./json.txt'));
?>
It can be built like this:
$arr = array(
array(
'id' => 123,
'info' => array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL'
)
),
array(
'id' => 456,
'info' => array(
'code' => 'ZDN',
'description' => 'test2',
'type' => 'CLR'
)
)
);
echo json_encode($arr);
Outputs
[
{
"id": 123,
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL"
}
},
{
"id": 456,
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR"
}
}
]
the JSON format you've specified in the first example (ie the requested format) is not valid JSON.
A valid JSON string must evaluate to a single Javascript object; the example you've given evaluates to two Javascript objects, separated by a comma. In order to make it valid, you would need to either enclose the whole thing in square brackets, to turn it into a JS array or enclose it in curly braces, and give each of the two objects a key.
The PHP code you've written is doing the second of these two options. It is therefore generating valid JSON code, about as close to the original request as could be expected while still being valid.
It would help if you'd shown us the PHP code that you've used to do this; without that, I can't really give you advice on how to improve it, but if you want to switch to the square bracket notation, all you need is to put your PHP objects into an unkeyed array, and json_encode() should do it all for you; you shouldn't need to use a keyed array or an iterator for that.
The only reason json_encode should produce the output you're seeing is adding another named key to the array that you're passing to json_encode, by default it should work as you want:
$json = '[
{
"id": "123",
"recall_info": {
"code":"ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "123",
"recall_info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
]';
$php = array(
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL',
'date' => '09/08/2012'
)
),
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test2',
'type' => 'CLR',
'date' => '16/02/2012'
)
)
);
var_dump(json_encode($php));