This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 6 years ago.
I use Microsoft Face API and I want to show data to final user, but how can I use foreach to atteint faceAttributes->age ?
There is an example of JSON file
[
{
"faceId": "c5c24a82-6845-4031-9d5d-978df9175426",
"faceRectangle": {
"width": 78,
"height": 78,
"left": 394,
"top": 54
},
"faceAttributes": {
"age": 71.0,
"gender": "male",
"smile": 0.88,
"facialHair": {
"mustache": 0.8,
"beard": 0.1,
"sideburns": 0.02
}
},
"glasses": "sunglasses",
"headPose": {
"roll": 2.1,
"yaw": 3,
"pitch": 0
}
}
}
]
I tried this code but not working :
<?php
$json = file_get_contents('file.json');
$data = json_decode($json);
if (count($data->faceAttributes)) {
// Cycle through the array
foreach ($data->faceAttributes as $idx => $faceAttributes) {
// Output a row
echo $faceAttributes->age ;
echo $faceAttributes->gender ;
?>
Thanks !
You don't have to iterate the object using foreach as the 'age' is a property of $data->faceAttributes itself.
Use this instead
if (count($data->faceAttributes)) {
echo $data->faceAttributes->age;
echo $data->faceAttributes->gender;
}
However, $data is an array and which $data you are using is actually $data[0]
So, if there is only one element in data array you can do
$data = $data[0] or $data = json_decode($json)[0]
Or, you can iterate through $data in case of more then one element.
Related
This question already has answers here:
Push associative array from for-loop in php
(2 answers)
how to append associative arrays into another array inside loop - php
(2 answers)
Insert values into an associative array within a loop
(7 answers)
Closed 3 years ago.
Trying to achieve this structure of jsondata based on an API I am trying to connect to:
{
"VoucherDate": "2019-10-27",
"VoucherText": "string",
"VoucherType": 2,
"Rows": [{
"AccountNumber": 0,
"DebitAmount": 0,
"CreditAmount": 0,
"TransactionText": "string"
},
{
"AccountNumber": 0,
"DebitAmount": 0,
"CreditAmount": 0,
"TransactionText": "string"
}
]
}
The code I have experimented with so far, below, generates this structure. The Rows array doesn't get the same structure as above, where do I do wrong?
{
"VoucherDate": "2019-10-31",
"VoucherText": "string",
"VoucherType": 2,
"Rows": [{
"TransactionText": "test"
}, {
"AccountNumber": 1000
}, {
"DebitAmount": 1
}, {
"CreditAMount": 2
}, {
"TransactionText": "test"
}, {
"AccountNumber": 1000
}, {
"DebitAmount": 1
}, {
"CreditAMount": 2
}]
}
Php code:
$postdata = array();
$postdata["VoucherDate"] = "2019-10-31";
$postdata["VoucherText"] = "string";
$postdata["VoucherType"] = 2;
$postdata["Rows"] = array();
for ($x = 1; $x <= 10; $x++) {
$postdata["Rows"][]["TransactionText"] = "string";
$postdata["Rows"][]["AccountNumber"] = 0;
$postdata["Rows"][]["DebitAmount"] = 0;
$postdata["Rows"][]["CreditAMount"] = ;
}
echo json_encode($postdata);
You need to add all of the elements into one array before adding them to your overall data, something like....
for ($x = 1; $x <= 10; $x++) {
$postdata["Rows"][] = ["TransactionText" => "string",
"AccountNumber" => 0,
"DebitAmount" => 0,
"CreditAMount" = 2];
}
I have 2 different jsons and I need to get one inside the other.
JSON 1
[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]
JSON 2
{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}
I need the second one inside the first one for use with javascript
I tried the array_merge() php function without getting results
since JSON1 is an array of JSON-object and JSON2 is just a JSON-object.
in addition to that you said, 'I need the second one inside the first one for use with javascript'. therefore, you can test this code https://3v4l.org/1HGNF/perf#output
please compare all performances in mem-usage and timing
$j1 = '[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]';
$j2 = '{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$j1 = json_decode($j1, true);
$j2 = json_decode($j2, true);
$j1[] = $j2;
var_dump(json_encode($j1));
You can use json_decode with parameter true to convert JSON into an array , then use array_merge to make them a single array
$j1 = '[{"id":"1","texto":"Vamos newells 17471934","fecha":"2019-06-24 12:09:12","categoria":"1","idpayment":"Reference_1561388952","provincia":"1","estado":"NO","email":"newells#gmail.com"}]';
$j1arr = json_decode($j1, true);
$j2 = ' {
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$j2arr = json_decode($j2, true);
$r = array_merge($j1arr[0], $j2arr);
You can use the merged array in javascript by using json_encode
json_encode($r)
https://3v4l.org/WKX1U
Do it simply like this way without any extra array merging methods-
<?php
$json1 = json_decode('[{"id":"1","texto":"Vamos newells 17471934","fecha":"2019-06-24 12:09:12","categoria":"1","idpayment":"Reference_1561388952","provincia":"1","estado":"NO","email":"newells#gmail.com"}]',1);
$json2 = json_decode('{"Texto":" VENDO O PERMUTO","imageJob":{"pathConvertido":"ClasificadosPNG/0011311247.png","convertido":true,"id":5011},"rubroClasificado":{"CodigoRubro":150,"id":76}}',1);
$json1[] = $json2; // add second json to first json
print_r($json1);
echo json_encode($json1);
?>
WORKING DEMO: https://3v4l.org/qhsJq
As you said you want to process the resulting data in JavaScript, and as per your question you want second json inside the first json. You can do something like this.
You will get a json as final result.
$first = '[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]';
$first = str_replace(['[',']','}'], '', $first);
$second = '{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$second = preg_replace('/\{/', ',', $second,1);
print_r($first.$second);
As result you will get a valid json, second json inside your first json, you can validate here
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I have the following JSON code:
{
"google.com": {
"clicks": 23,
"browsers": {
"Chrome": 19,
"Mozilla": 2,
"Safari": 1
}
},
"mcnitro.net": {
"clicks": 87,
"browsers": {
"Chrome": 19,
"Mozilla": 2,
"Safari": 1
}
}
}
And I am endeavouring to print on the document page the arrays' names and their children.
So far, I have tried the following PHP code:
<?php
header("Content-type: text/javascript");
$jsonString = file_get_contents('stats.json');
$data = json_decode($jsonString, true);
foreach($data->children() as $domain) {
echo $data[$domain];
foreach($data[$domain] as $value) {
echo $value['clicks'];
}
}
?>
However, I am facing an issue in the error_log:
PHP Fatal error: Call to a member function children() on array in /home/gamin167/public_html/ads/engine/300x250/gen.js.php on line 5
The result wanted was to have "google.com" and "mcnitro.net" printed, as well as their "clicks" property.
Any tip or advice will be highly appreciated! Thanks in advance!
You decode the string to an array with true yet you seem to try and use it as an object.
Also there is no need to loop twice.
foreach($data as $key => $domain) {
echo $key . "\n";
echo $domain['clicks'] . "\n\n";
}
output:
google.com
23
mcnitro.net
87
https://3v4l.org/D7FCY
You cannot use ->children(). $data is an array with your json data, and you can use foreach to get key and value, like foreach ($data as $key => $value).
So here, to get your domain name, just do :
<?php
header("Content-type: text/javascript");
$jsonString = file_get_contents('stats.json');
$data = json_decode($jsonString, true);
foreach($data as $domain => $value) {
echo $value['clicks'];
}
?>
Sorry for the noobie question, I am trying to save some json data on to my database. The problem is, i don't know how to get any of the "parent_names". The "parent_name" is always the same as the child "name".
price-data.json
[
{
"Flag": {
"name": "Flag",
"safe_price": "118.31",
"safe_net_price": "110.60",
"total_volume": 3148,
"7_days": {
"median_price": "118.31",
"lowest_price": "100.00",
"highest_price": "132.25",
"volume": 94
}
},
"Pole": {
"name": "Pole",
"safe_price": "81.21",
"safe_net_price": "70.62",
"total_volume": 1,
"7_days": {
"volume": 0
}
},
"Net": {
"name": "Net",
"safe_price": "0.89",
"safe_net_price": "0.84",
"total_volume": 763,
"7_days": {
"median_price": "0.89",
"lowest_price": "0.65",
"highest_price": "1.08",
"volume": 30
}
}
}
]
php
$filename = "price-data.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO table_all_prices(parent_name, name, safe_price, safe_net_price, total_volume, median_price, lowest_price, highest_price, volume) VALUES (
'".$row["parent_name"]."',
'".$row["parent_name"]["name"]."',
'".$row["parent_name"]["safe_price"]."',
'".$row["parent_name"]["safe_net_price"]."',
'".$row["parent_name"]["total_volume"]."',
'".$row["parent_name"]["7_days"]["median_price"]."',
'".$row["parent_name"]["7_days"]["lowest_price"]."',
'".$row["parent_name"]["7_days"]["highest_price"]."',
'".$row["parent_name"]["7_days"]["volume"]."'
)";
}
echo "All Prices inserted to database";
You need to access the key from the current array level in the loop, you can do that by
foreach($array as $parent_name => $row)
Adding a variable in before the $row variable think of this like array access
array( 'key' => 'value' )
Same deal. Now because you are in the "parent_name" level of the array you don't need to put the additional access key in there. So for this
$row["parent_name"]["7_days"]["volume"]
You can just do
$row["7_days"]["volume"]
Because you will be working in this part of the json
"name": "Net",
"safe_price": "0.89",
"safe_net_price": "0.84",
"total_volume": 763,
"7_days": {
"median_price": "0.89",
"lowest_price": "0.65",
"highest_price": "1.08",
"volume": 30
}
Then because you have an outer array wrapper on your json [{ .. }] those square brackets. you may need to do $array[0] or $array = reset($array). Reset is probably better ( if that turns out to be the case ) because you will avoid some warning messages from PHP if the array is empty. Essentially, trying to access a key of 0 will give you an undefined index warning if it's empty..
This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 8 years ago.
I like to sort following JSON data by it's value salary using PHP in ascending order.
{
"allresults": [
{
"results": [
{
"Name": "Peter",
"salary": 1000
}
]
},
{
"results": [
{
"Name": "Riya",
"salary": 999
}
]
}
]
}
Required Result:
Riya : 999
Peter : 1000
You can write a custom sort function using uasort. Something like this should work for you:
$data = json_decode($json, true);
uasort($data['allresults'], function($a, $b) {
$aSalary = $a['results'][0]['salary'];
$bSalary = $b['results'][0]['salary'];
return $aSalary - $bSalary;
});
foreach($data['allresults'] as $item) {
printf("%s: %d<br />", $item['results'][0]['Name'], $item['results'][0]['salary']);
}
play with this :
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(your_json($file, TRUE)),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($jsonIterator as $key => $val) {
//your control
}
1st json to php array -> $json_arr = json_decode($json, true);
after that -> you can use array_multisort http://php.net//manual/en/function.array-multisort.php