I have a php page which returns a php array as the following
array(6) {
[0]=>
array(2) {
["cityName"]=>
string(10) "Ananindeua"
[0]=>
string(10) "Ananindeua"
}
[1]=>
array(2) {
["cityName"]=>
string(8) "An�polis"
[0]=>
string(8) "An�polis"
}
[2]=>
array(2) {
["cityName"]=>
string(8) "Anderson"
[0]=>
string(8) "Anderson"
}
[3]=>
array(2) {
["cityName"]=>
string(6) "Angers"
[0]=>
string(6) "Angers"
}
[4]=>
array(2) {
["cityName"]=>
string(9) "Angoul�me"
[0]=>
string(9) "Angoul�me"
}
[5]=>
array(2) {
["cityName"]=>
string(6) "Anshan"
[0]=>
string(6) "Anshan"
}
}
I want to use this array in another page to do some ajax, and I want to encode the resulat into a JSON as the following :
{
"cityName": "Anshan",
"cityName": "Angoul�me",
"cityName": "Anderson",
"cityName": "An�polis",
"cityName": "Ananindeua"
}
but Instead I get only one value, which is the last value :
{
"cityName": "Anshan"
}
This is the code I tried :
<?php
$connexion = new PDO("mysql:host=localhost;dbname=world", 'root', 'toor');
$statement = $connexion->prepare("SELECT cityName FROM cities WHERE cityName LIKE '" . $_POST['cityName'] . "%'");
$statement->execute();
$resultats = $statement->fetchAll();
foreach($resultats as $city) {
$output[key($city)] = current($city);
}
echo json_encode($output, 128);
?>
So how can I solve this problem ?
Edit :
I tried to get only cities names, and push them into an array, when I do a var_dump() for this array this is what I get :
array(6) {
[0]=>
string(10) "Ananindeua"
[1]=>
string(8) "An�polis"
[2]=>
string(8) "Anderson"
[3]=>
string(6) "Angers"
[4]=>
string(9) "Angoul�me"
[5]=>
string(6) "Anshan"
}
But when I did a json_encode() I don't get anything, so I tried to do a var_dump(json_encode($output)); and I get this :
bool(false)
In the second time I tried to create a table manually :
$a = array("Ananindeua","Anápolis","Anderson","Angers","Angoulême","Anshan" );
and it worked.
But why the first array won't encode !
Your desired output is not valid/conceivable either as a PHP associative array or JSON because in both cases, you have duplicate keys.
You're just overwriting the cityName key with each iteration. Push to an array instead:
foreach($resultats as $city) {
$output[] = current($city);
}
echo json_encode($output, 128);
Output:
[
"Anshan",
"Angoulme",
"Anpolis"
]
Or if you want an object for each city, which is useful if you want other properties:
foreach($resultats as $city) {
$output[] = array(
'cityName' => current($city)
);
}
echo json_encode($output, 128);
Output:
[
{
"cityName" : "Anshan",
},
{
"cityName" : "Angoulme",
},
{
"cityName" : "Anpolis"
}
]
Side note: if you don't need the numerical keys from the PDO fetch call, consider using the PDO::FETCH_ASSOC fetch style, to bring back only associative keys:
$resultats = $statement->fetchAll(PDO::FETCH_ASSOC);
The json you're expecting doesn't look right. It should be:
[
{"cityName": "Anshan"},
{"cityName": "Angoul�me"},
{"cityName": "Anderson"},
{"cityName": "An�polis"},
{"cityName": "Ananindeua"}
]
and to generate this you need code like this:
foreach($resultats as $city) {
$item = new stdClass();
$item.cityName = current($city);
$output[] = item;
}
Your array's key is same (cityName), so the value getting replaced on each assignment.
use a numeric array, or another method that differentiating the key
e.g.,
foreach($resultats as $city) {
$output['cityName'][] = current($city);
}
output will be
{"cityName":
[
"Anshan",
"Angoulme",
"Anpolis"
]
}
The problem was that the table which I populate from database contains some accented characters, so the json_encode() failing.
The solution was to add charset=UTF8 in the first parameter of the PDO instance.
$connexion = new PDO("mysql:host=localhost;dbname=world;charset=UTF8", 'root', 'toor');
Related
When I encode the json data fetching from the mysql database, I get this:
[{"userid":"11","postid":"12"},{"userid":"13","postid":"12"},{"userid":"16","postid":"12"}]
And I am trying to get only the userid's like this: 11, 13, 16.
Decoding the json data gives me an output of: Array. And nothing else. When I var_dump this is my results:
array(3) {
[0]=> array(2) {
["userid"]=> string(2) "11"
["postid"]=> string(2) "12"
}
[1]=> array(2) {
["userid"]=> string(2) "13"
["postid"]=> string(2) "12"
}
[2]=> array(2) {
["userid"]=> string(2) "16"
["postid"]=> string(2) "12"
}
So I know there is data present, it's just not showing for some reason.
Here is what my query looks like:
if(isset($_POST['postuserid'])){
$uid = $_POST['postuserid'];
$ssql = "SELECT * FROM foodid WHERE postid=$uid";
$rresult = mysqli_query($db,$ssql);
while ($lrow = mysqli_fetch_assoc($rresult)){
$ret[] = $lrow;
$postjson = json_encode($ret);
$decode_postid = json_decode($postjson, true);
$new_postid = $decode_postid;
}
var_dump($new_postid);
die($new_postid);
// die($new_postid['userid']); is what I need along with all data userid fetched.
}
Is there a reason why this works when I encode json data, but not when I decode the json data?
Are you trying to get that array out of the die function? It can only take a string or int.
http://php.net/manual/en/function.exit.php
Your array is there... just do something like:
$ids = '';
foreach ($new_postid as $post) {
$ids .= $post['userid'] . ',';
}
$ids = rtrim($ids,',');
die($ids);
Try mapping those results:
$new_postid = $decode_postid;
$new_postid = array_map(function($item){
return $item['userid'];
}, $new_postid);
var_dump($new_postid);
Output
array(3) {
[0]=>
string(2) "11"
1=>
string(2) "13"
[2]=>
string(2) "16"
}
If you need to output as string, just use implode function
die(implode(',',$new_postid));
http://php.net/manual/en/function.array-map.php
I need to get the objects information for "label", "name" where value=true in a PHP variable and not were value=false.
How is this done with this JSON array?
If I make a var_dump of the JSON I get this:
array(8) {
[0]=>
object(stdClass)#8 (3) {
["label"]=>
string(4) "Name"
["name"]=>
string(7) "txtName"
["value"]=>
bool(true)
}
[1]=>
object(stdClass)#9 (3) {
["label"]=>
string(6) "E-mail"
["name"]=>
string(8) "txtEmail"
["value"]=>
bool(true)
}
[2]=>
object(stdClass)#10 (3) {
["label"]=>
string(12) "Phone Number"
["name"]=>
string(8) "txtPhone"
["value"]=>
bool(false)
}
[3]=>
object(stdClass)#11 (3) {
["label"]=>
string(19) "Mobile Phone Number"
["name"]=>
string(14) "txtMobilePhone"
["value"]=>
bool(false)
}
}
$arr = array();
$i = 0;
foreach($json as $key => $items) {
if($items->value == true) {
$arr[$i]['label'] = $items->label;
$arr[$i]['name'] = $items->name;
$i++;
}
}
You can decode it as an object or an array, in this example I use an array.
First you want to take the JSON encoded information and decode it into a PHP array, you can use json_decode() for this:
$data = json_decode($thejson,true);
//the Boolean argument is to have the function return an array rather than an object
Then you can loop through it as you would a normal array, and build a new array containing only elements where 'value' matches your needs:
foreach($data as $item) {
if($item['value'] == true) {
$result[] = $item;
}
}
You then have the array
$result
at your disposal.
Simplification of the suggestions proposed by users JohnnyFaldo and som:
$data = json_decode($thejson, true);
$result = array_filter($data, function($row) {
return $row['value'] == true;
});
I'm receiving a JSON and trying to interpret some values using PHP.
Example snippet from a JSON dump:
["11811"]=>
object(stdClass)#15 (11) {
["parent_area"]=>
NULL
["generation_high"]=>
int(19)
["all_names"]=>
object(stdClass)#16 (0) {
}
["id"]=>
int(11811)
["codes"]=>
object(stdClass)#17 (3) {
["ons"]=>
string(2) "08"
["gss"]=>
string(9) "E15000008"
["unit_id"]=>
string(5) "41421"
}
["name"]=>
string(10) "South East"
["country"]=>
string(1) "E"
["type_name"]=>
string(15) "European region"
["generation_low"]=>
int(1)
["country_name"]=>
string(7) "England"
["type"]=>
string(3) "EUR"
}
As there is lots of (nested) data, I need to obtain the value of ["name"] where ["type_name"] == 'European region'.
Thanks.
You could use array_filter()
$data_array = array(...);
function is_european($data) {
return $data->type_name == 'European region';
}
$filtered = array_filter($data_array,'is_european');
And then use filtered array to obtain values.
Maybe a better way would be to use JsonPath, like this, assuming your array is a result of decoding JSON (object):
$names = jsonPath($data_object, "$.[?(#['type_name'] == 'European region')].name");
Haven't tried this myself, it may need a bit of correction.
Try this:
<?php
$json = JSON_decode(str,true);
$arr = Array();
foreach($json as $f) {
/* eg. $f = $json["11811"] */
if($f['type_name'] == 'European region') {
$arr[] = $f['name'];
}
}
?>
I have this multidimension array in which I need to update a value. What would be the best way to do so? I tried it with 2 foreach loops but wasn't sure if that was the right approach.
Here is the array in question. I need to update the dollar amount on each sub array (i.e. add 3 to it).
array(6) { ["Ground"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "13.63" }
["3 Day Select"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "25.26" }
["2nd Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "32.43" }
["Next Day Air Saver"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "63.00" }
["Next Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "68.65" }
["Next Day Air Early AM"]=> array(2) { [0]=> string(3) "USD" [1]=> string(6) "103.68" } }
Your foreach loop approach would be correct, unless you expect the data format to change e.g. to have more nested levels. If that were the case, then a recursive function would be best suited.
Also, if the data is expected to remain uniform, you could do this:
foreach( $my_array as $index => $row ){
$my_array[$index][1] += 3;
}
cheers!
foreach ($arr as $k=>$row) {
$arr[$k][1] = floatval($row[1]) + 3;
}
foreach ($array as &$subarray) {
foreach ($subarray as $key=>&$value) {
// do whatever you want with $value
// ...
$value = 'something else'; // example
}
}
Try this:
<?php
foreach($first_array as $first_dem_key)
$first_array[$first_dem_key][1] = $first_array[$first_dem_key][1] + 3;
?>
$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[$rows['field1']] = $rows['field2'];
}
}
return $arr_tmp;
When I say var_dump($result) it has two values in array. But when I Execute arr_tmp it is returned with one value.
out put of ``var_dump($result)`
["param"]=>
array(4) {
["whcode"]=>
string(5) "001"
["mode"]=>
string(1) "A"
["stock_type"]=>
string(4) "AAA"
["process_name"]=>
string(7) "AAAA"
}
["record"]=>
array(2) {
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
[1]=>
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
}
}
output of var_dump (arr_tmp)
[1]=>
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
Both the array values seems to be same
I have the values overwriting in the array
Very hard to understand and read with the bad formatting, please take care to post it with proper formatting.
I think the answer is this:
$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[][$rows['field1']] = $rows['field2'];
}
}
var_dump($arr_tmp);
That should store both sets of data, you just needed to make it a multi-dimensional array. That is, if that is your question and I did not mis-read it through that garbled text above.
Update
This option is not recommended better to learn how to use arrays, simply posted for an example of usage:
$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
$i=0;
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[][$rows['field1'] . "_$i"] = $rows['field2'];
}
$i++;
}
var_dump($arr_tmp);