Pass array value in URL, http_build_query Not giving required results - php

I'm looking for script that can encode array values for keys. I need pass array value not key array for multiple values.
http_build_query will produce output like below:
&viewColumns%5B0%5D=date&viewColumns%5B1%5D=adv_responses
I need output like below:
&viewColumns=%5B%22date%22%2C%22adv_responses%22%5D
Please let me know if there is any solutions, the code is like this:
$data= array();
$data['group'] = 'cpcReportsAdvertiser';
$data['dimensions'] = array('date');
$data['viewColumns'] = array('date','adv_responses');
// $data['measures'] = ["adv_responses"];
$date = array('between',array('2019-07-01','2019-07-31'));
$dates = new stdClass;
$dates->date= $date;
$data['filters'] = $dates;
$data['attributes'] = [];
$sort = new stdClass;
$sort->column = 'adv_impressions';
$sort->direction = 'asc';
$data['sort'] = $sort;
$data['limit'] = 50;
$url = sprintf("%s?%s", $url, http_build_query($data));
print_r($url);exit;

To get viewColumns=%5B%22date%22%2C%22adv_responses%22%5D& which decodes to viewColumns=["date","adv_responses"] you would need to json_encode it:
$data['viewColumns'] = json_encode(array('date','adv_responses'));

Related

Transform a monodimensional PHP array into a multidimensional one

How would you transform a monodimensional array into a multidimensional array in PHP? Suppose you have something like this
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
And you want a function to transform it into
$array['breakfast'] = 'milk';
$array['meal']['firstdish'] = 'pasta';
$array['meal']['seconddish']['maincourse'] = 'veal';
$array['meal']['seconddish']['dressing'] = 'fries';
$array['meal']['dessert'] = 'pie';
The same function should of course transform
$tire['ean'] = '3286347717116';
$tire['brand.maker'] = 'BRIDGESTONE';
$tire['brand.model.name'] = 'POTENZA';
$tire['brand.model.variant'] = 'RE 040 RFT * SZ';
into
$tire['ean'] = '3286347717116';
$tire['brand']['maker'] = 'BRIDGESTONE';
$tire['brand']['model']['name'] = 'POTENZA';
$tire['brand']['model']['variant'] = 'RE 040 RFT * SZ';
I was thinking of using explode, then eval on the results, but eval always feels like cheating to me and I guess it would keep my code from running in HipHop.
The reason I want to do this is that I have to export lots of different tables from a database into XML files, and I already have a robust function that turns a multidimensional array into XML.
Like this:
function build(array &$trg, array $k,$key,$value) {
$p = &$trg;
while ( !empty($k) ) {
$nk = array_shift($k);
if ( !isset($p[$nk]) ) {
$p[$nk] = [];
}
$p = &$p[$nk];
}
$p[$key] = $value;
return $p;
}
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
$out = [];
foreach ($array as $key => $value ) {
$path = explode('.',$key);
$last = array_pop($path);
build($out,$path,$last,$value);
}
print_r($out);
You were on the right track with explode, but there's no need to use eval. Once you've got the pieces of the keys available, you can loop over them and incrementally assign a pointer into a new array:
<?php
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
$result = [];
$target = null;
foreach ($array as $key => $value) {
// Start by targeting the base of our resulting array
$target =& $result;
// Break the keys apart into pieces
$keyParts = explode('.', $key);
// Assign new target based on indexing into the result array one "piece" at a time
while ($part = array_shift($keyParts)) {
$target =& $target[$part];
}
// Finally, assign the value to our target
$target = $value;
}
See https://eval.in/625627

Multi-Dimensional Array -- PHP

I have the following occurring in a function I'm writing...
$eq_1_array = array();
$eq_1_array[] = $x_1;
$eq_1_array[] = $y_1;
$eq_1_array[] = $y_1_orig;
$eq_1_array[] = $z_1;
$eq_1_array[] = $z_1_orig;
$eq_1_array[] = $op_1;
$eq_2_array = array();
$eq_2_array[] = $x_2;
$eq_2_array[] = $y_2;
$eq_2_array[] = $y_2_orig;
$eq_2_array[] = $z_2;
$eq_2_array[] = $z_2_orig;
$eq_2_array[] = $op_2;
$sol_array = array();
$sol_array[] = $x_sol_val;
$sol_array[] = $y_sol_val;
$final_return_array[] = array();
$final_return_array[] = $eq_1_array;
$final_return_array[] = $eq_2_array;
$final_return_array[] = $sol_array;
return $final_return_array;
Basically, I should be getting 3 arrays from $final_return_array. However, the first array ($eq_1_array) is always empty.
If I do...
echo '<hr><hr>';
print_r($eq_1_array);
echo '<hr><hr>';
after $eq_1_array is populated, the proper data is there.
If I do...
echo '<hr><hr>';
print_r($final_return_array);
echo '<hr><hr>';
after $final_return_array is populated, the $eq_1_array array is empty.
Can the first element of a multi-dimensional array not by an array itself or something?
Your array assignment is incorrect. You're creating your array and assigning an empty array to the first element here:
$final_return_array[] = array();
It should be:
$final_return_array = array();

json value in php using json_encode

I have the below php code which outputs me a json array from freebase api.
<?php
public function search($query, $filter = '', $start = 0, $limit = 10, $exact = 'false'){
if(!empty($query)){
$service_url = 'https://www.googleapis.com/freebase/v1/mqlread?query=';
$append = "[{\"id\":\"$query\",\"key\":[{\"namespace\":\"/wikipedia/en_title\",\"*\":null}]}]";
$url = $service_url. $append;
return json_decode(file_get_contents($url), true);
}
}
}
$freebase = new Freebase();
$result = $freebase->search('/m/03np_7');
$obj = json_encode($result);
echo $obj;
?>
My $obj output is as below.
{"result":[{"key":[{"namespace":"\/wikipedia\/en_title","value":"University_of_Texas_at_Arlington","type":"\/type\/key"}],"id":"\/m\/03np_7"}]}
I am trying to get the value field alone using php. I tried json_decode but it was saying it accepts only string and I have an array. How can I get the value alone from the Json_encode?

Merge complex array php

I have a site developed in php (codeigniter) and I want to merge some array with same structure.
This is the constructor of my array:
$first = array();
$first['hotel'] = array();
$first['room'] = array();
$first['amenities'] = array();
/*
Insert data into $first array
*/
$second = array();
$second['hotel'] = array();
$second['room'] = array();
$second['amenities'] = array();
/*
Insert data into $second array
*/
After insert data I want to merge this array but the problem is that I have subarray inside it and I want to create a unique array like that:
$total = array();
$total['hotel'] = array();
$total['room'] = array();
$total['amenities'] = array();
This is the try to merge:
$total = array_merge((array)$first, (array)$second);
In this array I have only the $second array why?
Use the recursive version of array_merge called array_merge_recursive.
It seems like array_merge doesn't do what you think it does: "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one." Try this:
function merge_subarrays ($first, $second)
$result = array();
foreach (array_keys($first) as $key) {
$result[$key] = array_merge($first[$key], $second[$key]);
};
return $result;
};
Then call it as:
$total = merge_subarrays($first, $second);
and, if I've correctly understood your question, $total will contain the result you're looking for.
There is no standard way of doing it, you just have to do something like:
<?php
$first = array();
$first['hotel'] = array('hello');
$first['room'] = array();
$first['amenities'] = array();
/*
Insert data into $first array
*/
$second = array();
$second['hotel'] = array('world');
$second['room'] = array();
$second['amenities'] = array();
$merged = array();
foreach( $first as $key => $value )
{
$merged[$key] = array_merge( $value, $second[$key] );
}
print_r( $merged );

need to get json format from php

I am getting a json format like this
[{"service":{"title":"karthik","city":"chennai"}},{"service":{"title":"siva","city":"madurai"}}]
from code
$rt = array();
$rt["service"]["title"] = karthik;
$rt["service"]["city"] = chennai;
$t = array();
$t["service"]["title"] = siva;
$t["service"]["city"] = madurai;
echo json_encode(array($rt,$t));
but i need the same format of json result from this code
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id
FROM task");
while($row=mysql_fetch_array($a))
{
$jsonrow=new stdClass;
$jsonrow->title=$row['title'];
$jsonrow->city=$row['city'];
$jsonresponse=new stdClass;
$jsonresponse->service=$jsonrow;
}
echo json_encode(array($jsonresponse));
but the result actually i get from the above code is
[{"service":{"title":"Event Help","city":"Santa Fe"}}]
please someone help me on this issue.....
Use an array store all the values returned from the query
$array = array();
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id
FROM task");
while($row=mysql_fetch_array($a))
{
$jsonrow=new stdClass;
$jsonrow->title=$row['title'];
$jsonrow->city=$row['city'];
$jsonresponse=new stdClass;
$jsonresponse->service=$jsonrow;
$array[] = $jsonresponse;
}
echo json_encode(array($array));
you are overwriting $jsonresponse in your while loop, you should add this into array and json_encode this array
$response = array();
while( ... ){
...
$response[] = $jsonresponse;
}
echo json_encode($response);
try like this
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id FROM
task");
$jsonrow=new stdClass;
$jsonresponse=new stdClass;
while($row=mysql_fetch_array($a)) {
$jsonrow->title=$row['title']; $jsonrow->city=$row['city'];
$jsonresponse->service=$jsonrow;
}

Categories