I was trying to parsing json file below from a link but I still can't figure it out about parsing and display it with foreach.
data: [
{
id: "1072",
nik: "013977",
status: "",
name: "RAKHMAT KUSNADI",
birthdate: "1983-10-21",
email: "rakhmat.koes#gmail.com",
first_login: "0",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1102",
employee_id: "1072",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
{
id: "1069",
nik: "013377",
status: "",
name: "RENATA MARINGKA",
birthdate: "1987-05-20",
email: "",
first_login: "1",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1099",
employee_id: "1069",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
]
}
I want to display name and profile_pics where department id is 101.
Does anybody know how to parse it with foreach?
Reinventing the wheel, are we? Why not simply use:
$jsonObj = json_decode($jsonString);//returns stdClass instance, just an object
$jsonArr = json_decode($jsonString, true);//converts object to associative array
Read more on json_decode here... It's quite easy to use, really
If you decode the data to an array, you could loop through the data like so
while($item = array_shift($jsonArr))
{
foreach ($item as $key => $value)
{
echo $key.' => '.$value."\n";
}
}
Or simply use any old for/foreach loop on an object, its a traversable object anyway (though it doesn't implement the Traversable interface)
First step is to convert to an array
$data = json_decode($json);
Once you've got the array, you can then loop through it and check the values
$keepers = array();
foreach ($data as $item) {
if ($item->placement->department_id == 101) {
$keepers[] = $item;
}
}
Use json_decode
$arr = json_decode($jsonstring, true);
then use foreach loop
foreach($arr as $val) {
if($val['placement']['department_id'] == "101") {
//display what u want
}
}
Probably something like:
$data = json_decode($your_json);
foreach($data as $object) {
echo 'This is the name: ' . $object->name . PHP_EOL ;
}
$data = json_decode($json, true)
Then whatever info you want out you get out with the foreach loop
foreach ($data->id as $id)
{
echo $id;
}
With that you can set any variable like $data->nik as $nik or whatever you want then echo them back
usr this
foreach ($data->id as $id)
{
echo $id;
}
Related
Trying to get the a certain parameter in my multidimensional array... I have the following api request:
$responeAPI= ClientCode::request('post', 'responeAPI', $responeAPI,['debug'=>true]);
foreach ($responeAPI["buDetail"] as $key => $value){
$businessUserDet = $value["name"];
}
$storage['enterpriseList'] = $businessUserDet;
}
The array from the API response is like this:
{
"buList": {
"buDetail": [
{
"businessUserId": 2,
"name": "SAMPLENAME_231",
"parentBusinessUserId": 1,
"profileId": 2,
"profileName": "Enterprise"
}
]
},
"resultCode": 0,
"transactionId": "responeAPIs_1577358460"
}
I need to extract the "name" so I can use it for the $options parameter. Right now, my code isn't showing anything.
You can do like this using array_column
$jsonArray = '{"buList":{"buDetail":[{"businessUserId":2,"name":"SAMPLENAME_231","parentBusinessUserId":1,"profileId":2,"profileName":"Enterprise"},{"businessUserId":2,"name":"SAMPLENAME_231","parentBusinessUserId":1,"profileId":2,"profileName":"Enterprise"}]},"resultCode":0,"transactionId":"responeAPIs_1577358460"}';
$detais = json_decode($jsonArray, true);
print_r(array_column($detais['buList']['buDetail'], 'name', 'id'));
http://sandbox.onlinephpfunctions.com/code/458592622c78c67771cbf2e54661b9294c91e710
Could you change this line
foreach ($responeAPI["buDetail"] as $key => $value){
to
foreach ($responeAPI["buList"]["buDetail"] as $key => $value){
You can invoke as an object:
$array = '{ "buList": { "buDetail": [{ "businessUserId": 2, "name": "SAMPLENAME_231", "parentBusinessUserId": 1, "profileId": 2, "profileName": "Enterprise" } ] }, "resultCode": 0, "transactionId": "responeAPIs_1577358460" }';
$array = json_decode($array);
//for debug purposes only
echo var_export($array, true);
echo $array->buList->buDetail[0]->name;
Output: SAMPLENAME_231
Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);
I try to read IME field in PHP from following JSON FORMAT:
{"komentarji": [ {"RC_KOMENTARJI": [ {
"K_ID": 101,
"STATUS": "A",
"IME": "boris",
"E_MAIL": "test#example.com",
"KOMENTAR": "testni vnos",
"IP": "10.0.0.6",
"DATUM_ZAPISA": "2016-12-03T23:23:47Z",
"DATUM_UREJANJA": "2016-12-03T23:24:01Z"
},
{
"K_ID": 1,
"STATUS": "A",
"IME": "Peter",
"KOMENTAR": "Zelo profesionalno ste opravili svoje delo.",
"IP": "10.0.0.8",
"DATUM_ZAPISA": "2011-05-04T00:00:00Z"
}
] } ] }
How can I reach that field via foreach in PHP? Thank you.
Let you decode the json to object named $result.
If you want to read first IME then try this
$result->komentarji[0]->RC_KOMENTARJI[0]->IME
If you want to read all IME then you have to apply loop throw komentarji and RC_KOMENTARJI
Decode it by using json_decode().
$object = json_decode($json);
// result in object
$array = json_decode($json, true);
// result in array
You can try this:
$array = json_decode($json, true);
foreach ($array['komentarji'] as $key => $value) {
foreach ($value['RC_KOMENTARJI'] as $k => $val) {
echo $val['IME'] . "<br/>";
}
}
This will print:
boris
Peter
Hope it helps!!!
I have a json file which I decode using json_decode. The json file is an object which holds two arrays. I only want the first array but I'm having trouble figuring out how.
Json file
{
"app":{
"available":{
"stats":[
{
"name":"the name",
"at":"url"
},
{
"name":"the name",
"at":"url"
}
],
"stats2":[
{
"name":"the name",
"at":"url"
},
{
"name":"the name",
"at":"url"
}
]
}
}
}
I use
foreach($data3['app']['available'] as $name => $value)
{
foreach($value as $entry)
{
echo $entry['name'];
}
}
The output I get every name from both stats1 and stats2 arrays. I only want the names from stats1 array, not stats2. How can this be achieved?
because there are two arrays in app->available: stats and stats2
If you are interested in only stats, why don't you try:
foreach($data3['app']['available']['stats'] as $name => $value)
__UPDATE__
Try this one please
$in = '{"app":{"available":{"stats": [{"name":"the name","at":"url"},{"name":"the name", "at":"url"}],"stats2":[{"name":"the name","at":"url"},{"name":"the name","at":"url"}]}}}';
$obj = (array) json_decode($in, true);
foreach($obj['app']['available']['stats'] as $value)
{
foreach($value as $e => $v)
{
echo ($value['name'] );
echo ("\r");
}
}
I find it hard to explain but my page has a multidimensional array with all the users and I need to get values from the inner arrays without knowing the main key.
I'm not as experienced with arrays yet and I'm completely stuck right now. The function I use has 2 parameters. The first one is the input id of the user and the second is the array of the complete user list.
function userInfo($i, $users){
foreach($users['data'] as $user){
if($i = $user['id']){
return $user['SOMENAME?']['name'];
}
}
}
Here is a example of the array I'm working with:
{
"data": {
"Doe": {
"id": 266,
"title": "Doe title",
"name": "Doe",
"key": "Some key"
},
"John": {
"id": 412,
"title": "John title",
"name": "John",
"key": "Some key"
}
}
The function I have now simply returns Doe (The first value in the array) no matter how much arrays are in there.
How do I return the title or any of the other values when I don't know the name of the main key for that specific array?
There is an error in your if statement, where you are assigning a value, not ccomparing it (= vs == or ===).
For the purpose of your function, I don't think you need to know the key, because you're already in the array. eg.
function championInfo($i, $users){
foreach($users['data'] as $index => $user){
if($i == $user['id']){
return $user['name'];
}
}
}
foreach($users['data'] as $key => $user){
if($i = $user['id']){
return $champion[$key]['name'];
}
}
foreach($collecion as $key => $val){
That should get your results.
Try this;
foreach ($array as $key => $value) {
echo "ID: {$value['id']}, Title: {$value['title']}, Name: {$value['name']}, Key: {$value['key']}<br />";
}
another version (if you think this is more readable)
foreach ($array as $key => $value) {
list($id, $title, $name, $key) = array_values($value);
echo "ID: {$id}, Title: {$title}, Name: {$name}, Key: {$key}<br />";
}