How to convert into json object like array - php

Mycode is given below:
// seatsToCancel=U23,L43,U12
$tin='S4243534'; //Booking id
$seatsToCancel=$_GET['seatsToCancel'];
$seatArray=explode(",",$seatsToCancel);
$seatCount=count($seatArray);
$SeatsTocancel=implode ( '", "', $seatArray );
$params = array(
"tin"=>"$tin",
"seatsToCancel"=>array($SeatsTocancel)
);
echo $params=json_encode($params);
I want output like this:
{"tin":"S4243534" ,"seatsToCancel":["U23","L43","U12"]}

I assume your $seatArray is ["U23","L43","U12"]?
In that case you can do like this:
$seatArray = ["U23","L43","U12"];
$finalarray = ["tin"=>$tin,"seatsToCancel" => $seatArray];
echo json_encode($finalarray); //{"tin":"S4243534","seatsToCancel":["U23","L43","U12"]}
Edited to add the new requirement from edited question

So I'm guessing that your seats to cancel are coming in as a comma-separated list from the URL. So all you need to do is explode() the GET parameter to turn it into an array, place it as the value to a key and json_encode() it.
i.e.
$seatsToCancel = explode(',', $_GET['seatsToCancel']);
$params = [
'tin' => $tin,
'seatsToCancel' => $seatsToCancel,
];
$paramsJson = json_encode($params);
That should get you the result you're after:
{"tin":"S4243534" ,"seatsToCancel":["U23","L43","U12"]}
You may want to consider what happens if the GET parameter is empty and whether or not you want any additional error checking.

Related

php variable converting to JSON object

I want to make an array of json objects having the structure as follows:
{
"client-mac": "0C:D2:B5:68:73:24",
"client-dbm": "-82",
"clientManuf": "unknown"
}
I am using following php code to get this result:
$clientMac = $clients->{'client-mac'};
$clientStrength = $clients->{'snr-info'}->{'last_signal_dbm'};
$clientManuf = $clients->{'client-manuf'};
$jsonObject = array('client-mac' => $clientMac,
'client-dbm' => $clientStrength,
'clientManuf' => $clientManuf);
$jsonString = json_encode($jsonObject);
The problem is I am getting following json string:
{"client-mac":{
"0":"0C:D2:B5:68:73:24"
},
"client-dbm":{
"0":"-82"
},
"clientManuf":{"0":"Unknown"}
}
Why I am getting those extra keys as "0"? And how can I get my desired output? Thank you in advance :)
Apparently your source data has one more nested level with one key/value pair.
You could use reset on them to just pick the first value from that:
array('client-mac' => reset($clientMac),
'client-dbm' => reset($clientStrength),
'clientManuf' => reset($clientManuf));
That's because $clientMac, $clientStrength and $clientManuf are objects, not literal strings. You have to change the first three lines in the following way,
$clientMac = $clients->{'client-mac'}->{'0'};
$clientStrength = $clients->{'snr-info'}->{'last_signal_dbm'}->{'0'};
$clientManuf = $clients->{'client-manuf'}->{'0'};
...

How to fetch saved array from a file & access it like an array

I have a file, in which I saved data in array format and later I want to read this data into a variable and this variable must behave like an array.
Suppose I have a file on my pc : C:/test.txt and it contains an array :
Array
(
[first_name] => John
[last_name] => Doe
[email] => johndoe#gmail.com
)
Now I am fetching this data using below method :
$myfile = fopen("C:/test.txt", "r");
$test = fread($myfile,filesize("C:/test.txt"));
Now when I print $test it shows the data like array but when I check the datatype of this variable then it shows String.
I have also converted this variable into array using type casting :
$test1 = (Array) $test;
But when tried to fetch any index from $test1 then it show Illegal string error.
So can somebody help me out.
Try this
$file = "C:/test.txt";
$document = fopen($file,'r');
$contents = fread($document, filesize($file));
fclose($document);
this will give you a array $contents
print_r($contents);
C:/test.php
<?php
return array(
'first_name' => null,
'last_name' => null,
'email' => 'new',
);
another file:
<?php
$array = inclde('C:/test.php');
Or save json in file C:/test.json
{"first_name":null,"last_name":null,"email":"new"}
and in another file:
<?php
$json = file_get_contents('C:/test.json');
$array = json_decode($json, true);
Do this:
// $myarray is the array
file_put_contents('my_file', serialize($myarray));
// Later ...
$array = unserialize(file_get_contents('my_file'));
You can guess what serialize or unserialize does. But read more in docs to learn more specifically.
#VladimirKovpak 's answer will work too, but for simple arrays. Using serialization, you can save nearly any object, and get it back.
If you need more control over serialization process, look into magic methods __sleep and __wakeup from docs.

Echo array_values from array

I am very new in PHP and I was checking whether all my controlers are in so how can I echo this? what I tried resulting nothing
$controllers = array_intersect($json_api->get_controllers(), $active_controllers );
$return = array(
'json_api_version' => $version,
'controllers' => array_values($controllers)
);
echo $return['controllers']['controllers'];
use print_r function:
print_r($return['controllers']);
when you want read city you do:
$arr_controllers = $return['controllers'];
$key_2 = $arr_controllers[2];
where 2 is the key
If you want to print the values of an array with a
understandable format you should use print_r() instead of echo like so:
print_r($return['controllers']);
You can also use var_dump() to get some extra information about the fields, like the type and lenght.
If what you need is to asign a certain index of the array to a value just do something like this:
$variable = $return['controllers'][indexOfField]; // indexOfField=2 for city field
echo $variable;
For further information about print_r() check the official manual.

PHP Build url query from array

I'm trying to build URL query from an Array that looks like that:
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
I would like to get query like that:
localhost/get?serial=3804689&serial=3801239&serial=3555689
(you get the idea)
I'm trying to use http_build_query($serials, 'serial', '&'); but it adds the numeric index to the prefix 'serial'.
Any idea how to remove that numeric index?
Well you can't really have the same GET parameter in the string, After all if you try to access that variable server side, what would you use?
$_GET['serial'] - But which serial would it get?
If you really want to get a list of serials, Simply turn the array into a string, save it as an array and there you go. for example :
$serials = "string of serials, delimited by &";
Then you can use the http build query.
Maybe use a foreach:
$get = "localhost/get?serial=" . $serials[0];
unset( $serials[0] );
foreach( $serials AS serial ){
$get .= "&serial=$serial;
}
Just as an FYI, PHP doesn't handle multiple GET variables with the same name natively. You will have to implement something fairly custom. If you are wanting to create a query string with multiple serial numbers, use a delimiter like _ or -.
Ex: soemthing.com/serials.php?serials=09830-20990-91234-12342
To do something like this from an array would be simple
$get_uri = "?serial=" . implode("-", $serials);
You would be able to get the array back from a the string using an explode to
$serials = explode("-", $_GET['serials']);
Yes its quite possible to have such format, you have to build it query string by indices. Like this:
No need to build the query string by hand, use http_build_query() in this case:
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$temp = $serials;
unset($serials);
$serials['serial'] = $temp;
$query_string = http_build_query($serials);
echo urldecode($query_string);
// serial[0]=3804689&serial[1]=3801239&serial[2]=3555689&serial[3]=3804687&serial[4]=1404689&serial[5]=6804689&serial[6]=8844689&serial[7]=4104689&serial[8]=2704689&serial[9]=4604689
And then finally, if you need to process it somewhere, just access it thru $_GET['serial'];
$serials = $_GET['serial']; // this will now hold an array of serials
You can also try this
$get = "localhost/get?serial=";
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$list = implode("&serial=",$serials);
echo $get.$list;
Having the same GET parameter will not work this way. You will need to use an array in the get parameter:
localhost/get?serial[]=3804689&serial[]=3801239&serial[]=3555689
IF you just print $_GET through this URL, you will receive
Array ( [serial] => Array ( [0] => 380468 [1] => 3801239 [2]=> 3555689) )
Then you can do this to build your query string
$query_str = 'serial[]='.implode('&serials[]=',$serials);
You can try this version.
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$get = implode('&serials[]=',$serials);
echo 'test';
var_dump($_GET['serials']);
Result

How can I get an indexed array from query result in Kohana 3.2?

How can I get the INDEXED array result?
$qry1 = DB::select('name')->from('people')->execute();
$assoc_array = $qry1->as_array();
$object = $qry1->as_object();
// $indexed_array = [...]
Only for learning purposes, thanks.
It's like:
$indexed_result[0]; // Name
// $indexed_result[1];
// $indexed_result[2];
Do you want to get an array of names like array(0 => 'John', 1 => 'Sam')?
You should call $names = $gry1->as_array(NULL, 'name');
http://kohanaframework.org/3.3/guide/database/results#select-asobject-and-asassoc
The method as_assoc() will remove the object name and return the
results set back to an associative array. Since this is the default,
this method is seldom required.
So just do your execution.
But if you want only one row take a look at the current() method.

Categories