foreach on json data - json

Hi i want to insert values into table which is posted from api
json data is
{"questions":{"34":"Yes", "46":"good", "48":"NA", "29":"Yes", "45":"ravi", "49":"Negative", "43":"1 BHK", "35":"Neighbour", "38":"14", "39":"9", "27":"1",
"41":"Married", "52":"vijay#123.com", "47":"good", "31":"Bunglow", "33":"Middle Class", "37":"Owned By Parents", "30":"good", "50":"easy",
"51":"comments", "32":"No", "44":"[MusicSystem,PC,Refrigerator,Airconditioner]"}}
when i convert into array it is
Array
(
[questions] => Array
(
[34] => Yes
[46] => good
[48] => NA
[29] => Yes
[45] => ravi
[49] => Negative
[43] => 1 BHK
[35] => Neighbour
[38] => 14
[39] => 9
[27] => 1
[41] => Married
[52] => ravi#gmail.com
[47] => good
[31] => Bunglow
[33] => Middle Class
[37] => Owned By Parents
[30] => good
[50] => easy
[51] => comments
[32] => No
[44] => [MusicSystem,PC,Refrigerator,Airconditioner]
)
)
how to get this values like
using foreach
$question=34;
$answer= yes;

Try like this.Convert json into array using json_decode().And make a new array with key and value.Then just print the first key and value.
<?php
$json = '{"questions":{"34":"Yes", "46":"good", "48":"NA", "29":"Yes", "45":"ravi", "49":"Negative", "43":"1 BHK", "35":"Neighbour", "38":"14", "39":"9", "27":"1",
"41":"Married", "52":"vijay#123.com", "47":"good", "31":"Bunglow", "33":"Middle Class", "37":"Owned By Parents", "30":"good", "50":"easy",
"51":"comments", "32":"No", "44":"[MusicSystem,PC,Refrigerator,Airconditioner]"}}
';
$array = json_decode($json,TRUE);
//print_r($array);
foreach($array['questions'] as $key=>$value)
{
$arr[] = array('key'=>$key,'value'=>$value);
}
//print_r($arr);
echo "Question:".$arr[0]['key'].PHP_EOL;
echo "Answer:".$arr[0]['value'];
Output:
Question:34
Answer:Yes

To access a single value while having the key, you can do $array["questions"][34] to get the answer yes.
If you want to loop through all of them, you can do this loop:
foreach($array["questions"] as $no => $ans){
echo "Question: $no";
echo "Answer: $ans";
}

Related

How to unit test GraphQL responses on Lumen?

I'm trying to test an API I built with Lumen (PHP), but I'm stuck on unit test my GraphQL responses`.
This is what I have tried:
class MovieQueryTest extends Tests\GraphQLTestCase
{
use DatabaseMigrations;
public function testCanSearch()
{
Movie::create([
'name' => 'Fast & Furious 8',
'alias' => 'Fast and Furious 8',
'year' => 2016
]);
$response = $this->post('/graphql/v1', [
'query' => '{movies(search: "Fast & Furious"){data{name}}}'
]);
$response->seeJson([
'data' => [
'movies' => [
'data' => [
'name' => 'Fast & Furious 8'
]
]
]
]);
}
}
This is what I got:
PHPUnit 7.5.6 by Sebastian Bergmann and contributors.
F..... 6
/ 6 (100%)
Time: 690 ms, Memory: 24.00 MB
There was 1 failure:
1) MovieQueryTest::testCanSearch Unable to find JSON fragment
["data":{"movies":{"data":{"name":"Fast & Furious"}}}] within
[{"data":{"movies":{"data":[]}}}]. Failed asserting that false is
true.
The problem is that my data structure doesn't match the JSON's structure. While my data is inside an Array, the JSON's data is inside an Object and I can't figure out how to make it match:
["data":{"movies":{"data":{"name":"Fast & Furious 8"}}}]
[{"data":{"movies":{"data":[{"name":"Fast & Furious 8"}]}}}]
How can I make my data structure match the JSON's data structure or there is a better way to unit test GraphQL responses on Lumen?
You need to wrap 'name' => 'Fast & Furious 8' inside it's own array, for example:
The following:
$array = [
'data' => [
'movies' => [
'data' => [
['name' => 'Fast & Furious 8']
]
]
]
];
Should output:
{"data":{"movies":{"data":[{"name":"Fast & Furious 8"}]}}}

Get Json parameter

I need the message part of the json-string below. It should be possible with this, but it isn't.
echo $fb_response['data'][0]['message'];
[VGardena] => stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[message] => The traditional cuisine of Val Gardena - so much variety, so many different local specialities!nCome and visit us this summer at the Dolomites Market in Selva: goo.gl/6kMvsE
[story] => Val Gardena Gru00f6den added 3 new photos u2014 eating Strudel in Selva Wolkenstein.
[created_time] => 2017-04-16T17:11:00+0000
[id] => 105061549531699_1321349021236273
)
[1] => stdClass Object
(
[message] => ud83cudf37ud83cudf37ud83cudf37 Mbincion a duc na Bona Pasca! ud83cudf37ud83cudf37ud83cudf37nnu25ba Serena #Pasqua a tutti!nu25ba Wir wu00fcnschen euch allen Frohe #Ostern!nu25ba Wishing you a Happy Easter!
[story] => Val Gardena Gru00f6den celebrating Easter with Marina Demetz at Val Gardena Gru00f6den.
[created_time] => 2017-04-16T08:00:00+0000
[id] => 105061549531699_1328683843836124
)
)
[paging] => stdClass Object
(
[previous] => https://graph.facebook.com/v2.8/105061549531699/posts?limit=2&since=1492362660&access_token=EAACx6A6Hb9cBAB8tomDGj9N1FpE2xcWMVE7ad0Y2q08XUjVmGXsQ2aPCEKbX0iiRxK6M6FWYl1os3I2k5ZC1uY2cnJ1bZB2He3KTOpbwNo9KAZAzweShCUFvOt9Nfb2jZB8gHZCiO8l66dxsqdMCAbgxIlkTqJ8EZD&__paging_token=enc_AdCelydXbqb60yLCpaRWbTgLMBNNGGsZAfGqMO82Go1ZCA3ZAkSH6IS2TOBzqBSZA6SXXmltAcOE6ugchoDN3xGK1egG7qp8QtzqYD5u6YLeh9jBZAgZDZD&__previous=1
[next] => https://graph.facebook.com/v2.8/105061549531699/posts?limit=2&access_token=EAACx6A6Hb9cBAB8tomDGj9N1FpE2xcWMVE7ad0Y2q08XUjVmGXsQ2aPCEKbX0iiRxK6M6FWYl1os3I2k5ZC1uY2cnJ1bZB2He3KTOpbwNo9KAZAzweShCUFvOt9Nfb2jZB8gHZCiO8l66dxsqdMCAbgxIlkTqJ8EZD&until=1492329600&__paging_token=enc_AdBOpmW5OIQydpreytQ0eoWAdD9grbpMpB3XrkTTJL493qrDlacQCGVrn23ZBdZCKqgLxijwuQEnq5E1mwFaeiG2jRqdBvJmN2c7qu5UJQvIDnZBwZDZD
)
)
It should be possible with this, but it isn't.
No it shouldn’t, because you have an object here inside data, and not an array. (And data itself is also the property of an object.)
Object properties are accessed via -> in PHP.
$foo['VGardena']->data[0]->message

Ruby: Cleanup my code w/ stored procedure?

this is my first ruby script. I'd like to clean it up. How would I go about storing all of the following nessus_scans.insert() arguments into a variable to reduce duplicate lines in my code? I'd like to store :Id => "", :scan_title => "" etc all into this variable and then just do something like nessus_scans.insert(myvariable). This query is used about 5 times in the code which is why I want to simplify it. Thanks!
nessus_scans.insert(:Id => "",
:scan_title => "#{scan.title}",
:hostname => "#{host.hostname}",
:host_ip => "#{host.ip}",
:mac_addr => "#{host.mac_addr}",
:netbios_name => "#{host.netbios_name}",
:open_ports => "#{host.ports.map(&:inspect).join(', ').tr('"', '')}",
:operating_system => "#{host.operating_system}",
:start_time => "#{host.start_time}",
:stop_time => "#{host.stop_time}",
:runtime => "#{host.runtime}",
:cve => "#{event.cve}",
:cvss_base_Score => "#{event.cvss_base_score}",
:description => "#{event.description}",
:family => "#{event.family}",
:plugin_id => "#{event.plugin_id}",
:output => "#{event.output}",
:event_name => "#{event.name}",
:patch_publication_date => "#{event.patch_publication_date}",
:plugin_version => "#{event.plugin_version}",
:event_port => "#{event.port.number}",
:risk => "#{event.risk}",
:see_also => "#{event.see_also}",
:severity => "#{event.severity.in_words}",
:solution => "#{event.solution}",
:synopsis => "#{event.synopsis}",
:xref => "#{event.xref}",
:bool_crit => "#{event.critical?}",
:bool_high => "#{event.high?}",
:bool_med => "#{event.medium?}",
:bool_low => "#{event.low?}",
:bool_info => "#{event.informational?}")
end # end event.informational?
my_data = {
Id: "",
scan_title: scan.title,
hostname: host.hostname,
...
}
nessus_scans.insert(my_data)
These are all equivalent:
def method(arg1, arg2)
p arg1, arg2
end
method(10, a: 20, b:30)
--output:--
10
{:a=>20, :b=>30}
method(10, {a: 20, b:30})
--output:--
10
{:a=>20, :b=>30}
data = {a: 20, b:30}
number = 10
method 10, data
--output:--
10
{:a=>20, :b=>30}

Not all POST array elements getting sent

I have a table which has 4 columns with the first column containing a text input boxes. The entire table is wrapped inside a form that will run a PHP script on that data. As of right now, I'm just printing out the POST array. The problem is that I'm missing some of the values that I write into the input fields. So putting the values 1-10 in the first 10 text inputs gives me the following in print_r:
Array
(
[65710] =>
[65705] => 2
[269200318] =>
[269200586] => 4
[16830189] =>
[16829165] =>
[1051902] => 7
[65742] =>
[16830122] =>
[269339822] => 10
}
The HTML for this form can be found here: http://jsfiddle.net/nY9MF/
This is running on IIS 7
Edit: I updated the jsfiddle code to have the full table for one of these stores. This is the POST array after I hit submit:
Array(
[65710] =>
[65705] => 2
[269200318] =>
[269200586] => 4
[16830189] =>
[16829165] =>
[1051902] => 7
[65742] =>
[16830122] =>
[269339822] => 10
[65774] =>
[16821982] =>
[65740] =>
[16825517] =>
[65709] =>
[1051326] =>
[1052334] =>
[65773] =>
[4110] =>
[16837342] =>
[16825518] =>
[1051375] =>
[1051594] =>
[65743] =>
[1052108] =>
[256] =>
[4106] =>
[65711] =>
[65738] =>
[1051597] =>
[4109] =>
[65724] =>
[SaveQuantity] => Save
)

PHP don't generate properly array from database (UBUNTU)

I have a little problem.
There are two tables in my database: users and classes. The first one contains info about users, and the second one - about user classes and about access rights.
Now I'm extracting all data from there using this:
SELECT * FROM users NATURAL JOIN classes WHERE users.ID_User = '$id';
The mysql code works and returns a right array.
Now, when I'm doing next:
<?php
$result = mysql_query($sql_above);
$row = mysql_fetch_array($result);
print_r($row);
?>
... i'm getting this:
Array ( [0] => 1 [ID_User] => 1 [1] => John [Name] => John [2] => Doe [Surname] => Doe [3] => ... [16] => Owner [Class] => Owner [17] => [All] => [18] => [CanAuth] => [19] => [CanViewData] => [20] => [CanAddData] => [21] => [CanAlterData] => [22] => [CanDeactivateData] => [23] => [CanDeleteData] => [24] => [CanMgLocatari] => ... )
Columns from 17 till the end are access rights, noted in the database by 1 or 0. And there, they're missing.
Is there any option to enable in PHP configuration to correct this thing? Because on a Windows machine, the code executes properly and rights are working.
PHP Version 5.3.6-13ubuntu3.7 | Apache/2.2.20 (Ubuntu) | MySQL client version: 5.1.62
Please, reply. Thanks!