convert an array of arrays to json - php

i want to convert this array as shown below
array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));
into this format:
"3":{"Egypt":{"7":Tanta,"1000":"other"}},"80":{"India":{"0":"All","1":Ahmedabad}}
I am using PHP and not able to figure out how can i do this. I have used json_encode. but the results are not correct.I am using PHP as my language.
thanks in advance

Before converting into json, you should change the array:
$array_countries_formated = array();
foreach ($array_countries as $item)
{
$array_countries_formated[$item['cntryValue']][$item['cntryLabel']][$item['value']] = $item['label'];
}
echo $array_countries_formated = json_encode($array_countries_formated, JSON_FORCE_OBJECT);
Result:
{"3":{"Egypt":{"7":"Tanta","1000":"Other"}},"80":{"India":{"0":"All","1":"Ahmedabad"}}}

Try this...
<?php
$array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));
$jsonString = json_encode($array_countries);
print_r($jsonString);
?>
Result:
{"20":{"cntryValue":"3","cntryLabel":"Egypt","value":"7","label":"Tanta"},"21":{"cntryValue":"3","cntryLabel":"Egypt","value":"1000","label":"Other"},"22":{"cntryValue":"80","cntryLabel":"India","value":"0","label":"All"},"23":{"cntryValue":"80","cntryLabel":"India","value":"1","label":"Ahmedabad"}}

If I understand your requested output correctly, the following should do the trick:
$result = array();
foreach ($array_countries as $country) {
$cntryValue = $country["cntryValue"];
if (!array_key_exists($cntryValue, $result)) {
$result[$cntryValue] = array();
}
$result[$cntryValue][$country["cntryLabel"]] = array();
$result[$cntryValue][$country["cntryLabel"]][$country["value"]] = $country["label"];
}
echo json_encode($result) . "\n";
A little explanation: the array provided ($array_countries) is formatted differently as compared to your requested output. Therefore, it should be converted. That is what the foreach loop does. The formatted result can be converted to json using the json_encode function.

Related

MYSQLI/PHP How do I have to define my query/statement to output every message that was sent in a particular chatroom? [duplicate]

for output array Instead of using json_encode, use of what.(how is output(echo) array without use of json_encode?)
i use of codeigniter.
CI_Controller:
function auto_complete(){
$hotel_search = $this->input->post('search_hotel');
echo json_encode($this->model_tour->auto_complete($hotel_search));
// if use of json_encode output is '[{"name":"salal"},{"name":"salaso"},{"name":"salasi"},{"name":"salsh"}]' if don want use of json_encode output is "Array"
}
CI_model:
function auto_complete($hotel_search)
{
$query_hotel_search = $this->db->order_by("id", "desc")->like('name', $hotel_search)->get('hotel_submits');
if($query_hotel_search->num_rows()==0){
return '0';
}else{
$data = array();
foreach ($query_hotel_search->result() as $row)
{
$data[] = array('name' => $row->name);
}
return $data;
}
}
If you just want to view the array, print_r($array) or var_dump($array) will work
I'm not sure if this is what you are looking for, but it really helps show the structure of the array/JSON:
echo "<pre>";
print_r($array);
echo "</pre>";
It will show the $array broken out and will keep the tabbing so you can see how it's nested.
If you want to view the contents of the array, use print_r or vardump
If you want to do something useful with the information, you're going to have to loop through the array
foreach($this->model_tour->auto_complete($hotel_search) as $key => $value){
//do something
}
foreach($array as $key => $value)
{
echo $key . ' = ' . $value . "\n";
}
That will give you the array as string.
You can also use print_r()
print_r($array);
or var_dump()
var_dump($array);
You have a few options at your disposal:
json_encode (which you mention yourself)
print_r or var_dump (timw4mail mentions this)
implode (however, this won't work for nested arrays, and it will only display the keys)
a combination of array_map (to format individual array elements using your own function) and implode (to combine the results)
write your own recursive function that flattens an array into a string
If you're using jQuery, any .ajax(), .get(), or .post() function will try to guess the data type being returned from the HTTP request. Set the content type of your controller to JSON:
$hotel_search = $this->input->post('search_hotel');
$this->output
->set_content_type('application/json')
->set_output( json_encode($this->model_tour->auto_complete($hotel_search)) );

Extracting JSON response from JSON Object in PHP [duplicate]

for output array Instead of using json_encode, use of what.(how is output(echo) array without use of json_encode?)
i use of codeigniter.
CI_Controller:
function auto_complete(){
$hotel_search = $this->input->post('search_hotel');
echo json_encode($this->model_tour->auto_complete($hotel_search));
// if use of json_encode output is '[{"name":"salal"},{"name":"salaso"},{"name":"salasi"},{"name":"salsh"}]' if don want use of json_encode output is "Array"
}
CI_model:
function auto_complete($hotel_search)
{
$query_hotel_search = $this->db->order_by("id", "desc")->like('name', $hotel_search)->get('hotel_submits');
if($query_hotel_search->num_rows()==0){
return '0';
}else{
$data = array();
foreach ($query_hotel_search->result() as $row)
{
$data[] = array('name' => $row->name);
}
return $data;
}
}
If you just want to view the array, print_r($array) or var_dump($array) will work
I'm not sure if this is what you are looking for, but it really helps show the structure of the array/JSON:
echo "<pre>";
print_r($array);
echo "</pre>";
It will show the $array broken out and will keep the tabbing so you can see how it's nested.
If you want to view the contents of the array, use print_r or vardump
If you want to do something useful with the information, you're going to have to loop through the array
foreach($this->model_tour->auto_complete($hotel_search) as $key => $value){
//do something
}
foreach($array as $key => $value)
{
echo $key . ' = ' . $value . "\n";
}
That will give you the array as string.
You can also use print_r()
print_r($array);
or var_dump()
var_dump($array);
You have a few options at your disposal:
json_encode (which you mention yourself)
print_r or var_dump (timw4mail mentions this)
implode (however, this won't work for nested arrays, and it will only display the keys)
a combination of array_map (to format individual array elements using your own function) and implode (to combine the results)
write your own recursive function that flattens an array into a string
If you're using jQuery, any .ajax(), .get(), or .post() function will try to guess the data type being returned from the HTTP request. Set the content type of your controller to JSON:
$hotel_search = $this->input->post('search_hotel');
$this->output
->set_content_type('application/json')
->set_output( json_encode($this->model_tour->auto_complete($hotel_search)) );

Accessing first element of stdobject

I am using an API where I get the following response:
{"BTC_LTC":{"last":"0.0251","lowestAsk":"0.02589999","highestBid":"0.0251","percentChange":"0.02390438",
"baseVolume":"6.16485315","quoteVolume":"245.82513926"},"BTC_NXT":{"last":"0.00005730","lowestAsk":"0.00005710",
"highestBid":"0.00004903","percentChange":"0.16701570","baseVolume":"0.45347489","quoteVolume":"9094"}, ... }
It is no problem to access the object when I would know the key like
$result = json_decode(file_get_contents($url));
$result->BTC_LTC->last
In my case I do not know the XXX_XXX keys. How can I get the keys? I tried things like $result->{0} / $result->[0] / $result{0} / $result[0] without success.
How can I retrieve the values of XXX_XXX (e.g. in the example above BTC_LTC)?
This should do the trick:
<?php
$json = '{"BTC_LTC":{"last":"0.0251","lowestAsk":"0.02589999","highestBid":"0.0251","percentChange":"0.02390438",
"baseVolume":"6.16485315","quoteVolume":"245.82513926"},"BTC_NXT":{"last":"0.00005730","lowestAsk":"0.00005710",
"highestBid":"0.00004903","percentChange":"0.16701570","baseVolume":"0.45347489","quoteVolume":"9094"}}';
$result = json_decode($json);
$vars = get_object_vars($result);
$keys = array_keys($vars);
echo $vars[$keys[0]]->last;
?>
You can try the code here
Use a foreach loop that should work
foreach($result as $k=>$v)
{
.
.
.
}
The second argument to json_decode allows specifying that you want an array returned:
$result = json_decode(file_get_contents($url),true);
Now that result is an array you can use it as usual (looping, array_keys, e.t.c.).

json decode with an array in php

I am having a problem with getting data from json. I cant change the way it is saved in the database since it is generated by the framework and after that read for the fields generation. My json looks like this:
{"102":{"textinput":{"comment":"2"}},"104":"34"}
OR
{"78":{"textinput":{"comment":"1"}},"82":"34"}
Comment value is my serialnumber that I net to get from this json. I tried with :
$json_sn = json_decode($customer_json_sn, true);
$snr = $json_sn['78']['textinput']['comment'];
But this is not the solution I need, since I never know the value of first numeric key, I cant rely on that. Any help would be appreciated.
If this format is going to be always the same, you can use reset() function on this one. Consider this example:
$json_sn = json_decode($customer_json_sn, true);
$snr = reset($json_sn);
echo $snr['textinput']['comment'];
How about:
$snr_array = array()
foreach ($json_sn as $key)
snr_array[] = $key['textinput']['comment'];
Edit: I just realized that you might just need/get one comment:
$key = key($json_sn);
$snr = $json_sn[$key]['textinput']['comment'];
You can do:
<?php
$json = '{"78":{"textinput":{"comment":"1"}},"82":"34"}';
var_dump(json_decode($json, true));
$data = json_decode($json, true);
foreach( $data as $key => $value ) {
# Check if exsit
if (isset($value['textinput']['comment'])) {
echo "Value: " . $value['textinput']['comment'];
}
}

Add values to array via foreach

I'm trying to add values to an array via foreach but it only returns the word "Array" not the actual strings.
$msg = array();
foreach ($results as $result) {
$inventory = $result->qoh;
$inventoryOrder = $result->qo;
$product = $result->item;
$totalinv = $inventory+$inventoryOrder;
if ($inventory <= $threshold) {
$message = "Inventory for $product has fallen beneath threshold. $inventory remaining.\n";
$msg[] = array($message);
}
}
print (array_values($msg));
I've tried a few different ways and everytime it returns the word "Array"
You should use print_r, not print. print is for stings only. Try this:
echo '<pre>'; print_r(array_values($msg)); echo '</pre>';
Use var_dump to see the values.
var_dump (array_values($msg));
var_dump will alway show you the type of the result too. Helps a lot in debugging. (Looking at your code, I'm assuming you are doing the same).
I think you need to change the following code:
$msg[] = array($message);
to
array_push($msg, $message);

Categories