How to pass multidimensional values to a json array? - json

I am trying to pass the value to an api through json request.
$payload = json_encode( array("phones"=> "971xxxxxxx",
"emails"=> "fadfad#xyz.com",
"id"=> "1"
) );
How will i pass the below multi dimensional values to a json request like the above code?
{ "contactList": [ { "phones" : ["+91 9000000034"], "emails" : [fadfad#xyz.com], "id" : 1 }, { "phones" : ["+91 903-310-00-001"], "emails" : [krs#xyz.in], "id" : 2 } ] }

Store the data as nested / multidimensional arrays before passing it to json_encode.
$array = array();
$array["contactList"] = array(
array( "phones"=> "971xxxxxxx",
"emails"=> "fadfad#xyz.com",
"id"=> "1"
),
array( "phones"=> "+91 903-310-00-001",
"emails"=> "krs#xyz.in",
"id"=> "2"
)
);
$payload = json_encode($array);
echo $payload;
produces
{"contactList":[{"phones":"971xxxxxxx","emails":"fadfad#xyz.com","id":"1"},{"phones":"+91 903-310-00-001","emails":"krs#xyz.in","id":"2"}]}
If you need to hold values like the phone numbers inside an array, simply wrap them in an array.

Related

Loop on a variable delimited with gamma using Laravel 8

I have in my database values with this form :
["email1#gmail.com","email2#gmail.com"]
I'm using laravel and I want to loop on this variable to get each element for example get the element : email1#gmail.com.
I tried the following code :
I have the following array :
$emails :
array:2 [▼
0 => "["email1#gmail.com","email2#gmail.com"]"
1 => "["email3#gmail.com","email4#gmail.com"]"
]
So I'm using the following code to get each element :
$var = array();
foreach ($emails as $key => $value) {
$var[] = $value;
}
I get the following result :
array:2 [▼
0 => "["email1#gmail.com","email2#gmail.com"]"
1 => "["email3#gmail.com","email4#gmail.com"]"
]
If you have any idea , please help
UPDATE
I have the following array :
array:2 [▼
0 => "["email1#gmail.com","email2#gmail.com"]"
1 => "["hajar.boualamia33#gmail.com","guernine.khadija#gmail.com"]"
]
And I did the following method :
$emailss = collect($emails)->flatten()->all();
dd($emailss);
I get the following result :
array:2 [▼
0 => "["email1#gmail.com","email2#gmail.com"]"
1 => "["hajar.boualamia33#gmail.com","guernine.khadija#gmail.com"]"
]
Update
Ha, tricky one. It seems that you have a PHP expression (an array) stored. So in order to extract the arrays, we need to evaluate them first.
Try this instead:
$elements = [
"['email1#gmail.com','email2#gmail.com']",
"['email3#gmail.com','email4#gmail.com']",
];
$emails = collect($elements)
->map(function ($element) {
return (eval("return \$element = " . $element . ';'));
})
->flatten()
->all();
Try this:
$elements = [
['email1#gmail.com','email2#gmail.com'],
['email3#gmail.com','email4#gmail.com'],
];
$emails = collect($elements)->flatten()->all();
This will get you:
=> [
"email1#gmail.com",
"email2#gmail.com",
"email3#gmail.com",
"email4#gmail.com",
]
Check this method on the docs.

insert multiple columns table laravel

i was wondering how can i insert an array of data into one table by using of 2 array like this in laravel model
$attributes =array('title','description');
$options =array('test','blahblahblah');
the table would be like
title test
description blahblahblah
so far i reach to this
$values = array(
array($attributes => $options),
);
but it says
Illegal array key type array less
Arrays and objects can not be used as array keys.
any way i try has different error
but the most of the errors is illegal offset type
do you have any suggestion?
You can combine both arrays with array_combine. It will take an array for the keys and one array for the values.
$attributes = array('title', 'description');
$options = array('test', 'blahblahblah');
$values = array_combine($attributes, $options);
Result:
array:2 [▼
"title" => "test"
"description" => "blahblahblah"
]
You can try this:
First you have to combine array as following:
$tableFields = array('title', 'description');
$fieldValues = array('test', 'blahblahblah');
$newArr = array_combine($tableFields, $fieldValues);
Output :
array:2 [▼
"title" => "test"
"description" => "blahblahblah"
]
Then insert into table as following:
DB::table('table_name')->insert($newArr);

How to parse JSON/REST data from server using Perl

Im trying to parse out JSON output from the server using Perl. The connection and downloading of the REST data is ok, I just need help parsing the returned data. Here is the snippet for my code:
my $response = HTTP::Tiny->new->get($SERVER_ADDR);
if ($response->{success})
{
my $html = $response->{content};
#LINES = split /\n/, $html;
chomp(#LINES);
print("Lines: '#LINES'\n"); # ZZZ
my $decoded_json = decode_json( $html );
print Dumper $decoded_json;
}
else
{
print "Failed: $response->{status} $response->{reasons}";
}
And here is the results:
Lines: '{"players":[{"currentlyOnline":false,"timePlayed":160317,"name":"MarisaG","lastPlayed":1474208741470}]}'
$VAR1 = {
'players' => [
{
'currentlyOnline' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
'timePlayed' => 160317,
'lastPlayed' => '1474208741470',
'name' => 'MarisaG'
}
]
};
There will be multiple entries under the "players" for each player logged in right now. Any tips?
I'm not really sure what you're asking. You have successfully parsed the JSON by by calling decode_json(). You now have a data structure in $decoded_json. Your call to Dumper() shows the structure of that data. It's a hash reference with a single key, players. The value associated with that key is an array reference. Each element in the referenced array is another hash.
So, for example, you could print all of the players' names with code like this.
foreach (#{ $decoded_json->{players} }) {
say $_->{name};
}

json cannot be decode

I have a problem with json,
I'm using PHP Curl to post file with form-data, and after post the Curl return some weird json
like this
{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}
the problem is, the return result can't be json_decode, I know if this json weird, I can print but cannot be json_decode,
I not have acces to change API, I need the id from badges,
is there any trick? or a way to get the id, or some modified so the return result can be decode
i have tried
$a = 'that result';
$b = "'".$a."'";
$c = json_decode($b);
but it still json format, not become array
need some idea and help, thx
EDITED:
let's say
$result = {"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}
when I json_decode
$data = json_decode($result);
var_dump($result );
print_r($data);
it will return
{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}bool(true) 1
try this
$js='{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}';
var_dump(json_decode($js,true));
Your Output will be
array (size=3)
'code' => int 200
'status' => string 'Success' (length=7)
'badges' =>
array (size=6)
'id' => string '0d28f02d13fe4c7ca8681e2ed0224180' (length=32)
'name' => string 'test 5' (length=6)
'description' => string 'test 5' (length=6)
'image' => string 'http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg' (length=66)
'category' => string 'Upload' (length=6)
'target' => int 2
You don't want to put quotes around the string. Change
$a = 'that result';
$b = "'".$a."'";
$c = json_decode($b);
to simply
$a = 'that result';
$c = json_decode($a);
The JSON is valid. Putting the quotes around it made it invalid.
The original response is correct JSON syntax. Don't add the extra quotes in $b = "'".$a."'"; //INCORRECT
Instead try this, as an example:
/* $response is the result from API */
$response = '{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180"}}';
$decoded = json_decode($response);
print_r($decoded); //See full decoded
$badge_id = $decoded->badges->id;
echo "The badge id is $badge_id \n";
Which would print:
stdClass Object
(
[code] => 200
[status] => Success
[badges] => stdClass Object
(
[id] => 0d28f02d13fe4c7ca8681e2ed0224180
)
)
The badge id is 0d28f02d13fe4c7ca8681e2ed0224180

Encode complex JSON structure using Perl

I want to encode the result of a MySQL query into a JSON string using JSON::XS. The JSON string needs to look like this
{
"database" : "dbname"
"retentionPolicy" : "mytest",
"tags" : {
"type" : "generate",
"location" : "total",
"source" : "ehz"
},
"points" : [{
"precision" : "ms",
"timestamp" : "ts1",
"name" : "power",
"values" : {
"value" : "val1"
}
}, {
"precision" : "ms",
"timestamp" : "ts2",
"name" : "power",
"values" : {
"value" : "val2"
}
}, {
"precision" : "ms",
"timestamp" : "ts3",
"name" : "power",
"values" : {
"value" : "val3"
}
}
]
}
The points array with each point's values element is giving me immense headaches.
Here is the code block that generates the JSON
my %json_body = (
'database' => $db_name,
'retentionPolicy' => $retention,
'tags' => {
'source' => $metric_source,
'type' => $metric_type,
'location' => $metric_location
}
);
# loop through mysql result
while ( ($timestamp, $value) = $query->fetchrow_array() ) {
my %json_point1 = (
'name' => $series_name,
'timestamp' => ($timestamp * 1),
'precision' => "ms"
);
%json_point2 = ('value' => $value);
%json_values = (%json_point1, 'values' => \%json_point2);
push(#all_values, \%json_values);
}
$query->finish();
# Encode json
my %json_data = (%json_body, "points" => \#all_values);
$influx_json = encode_json(\%json_data);
I think the line push(#all_values, \%json_values) is my problem. If I pass %json_data as a hash reference, only the last value from the while loop is retained. If I use %json_values directly, the encoded JSON is messed up because it loses the structure.
Any hint would be appreciated. And please bear with me: this array and hash references are already making my head explode.
I'm pretty sure you problem will be because you're using a globally scoped hash for %json_point and %json_point2.
You see, the root of this is - you simply don't get a list of hashes. You get a list of hash references.
So the problem here is - when you push a reference to your hash into #all_values - you're pushing the same reference each time. But then you're overwriting the contents of the hash that you're referencing.
Try this:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %hash_thing;
my #all_values;
for ( 1..3 ) {
%hash_thing = ( "test" => $_ );
push ( #all_values, \%hash_thing ) ;
}
print join ( "\n", #all_values );
print Dumper \#all_values;
And you'll see you have the same 'value' 3 times:
HASH(0x74478c)
HASH(0x74478c)
HASH(0x74478c)
And so if you dump it, then of course - you don't get the right array - and so your encoded JSON doesn't work either.
$VAR1 = [
{
'test' => 3
},
$VAR1->[0],
$VAR1->[0]
];
The simplest fix is to use my to scope the hashes to the loop. (And turn on use strict; and use warnings if you haven't.)
Alternatively, you can use a hash reference like this:
my #all_values;
my $hash_ref;
for ( 1..3 ) {
$hash_ref = { "test" => $_ };
push ( #all_values, $hash_ref ) ;
}
print #all_values;
print Dumper \#all_values;
Because $hash_ref is a scalar, and it's a reference to an anonymous hash, it can be inserted into the array by value, rather than by reference.