Parsing array value with PHP in a foreach loop - php

I want to parse an array with PHP's foreach loop to get the object names and values inside the 'ques' array.I want
[
{
"ques": [
{
"name": "comment",
"value": "comment me for the reason",
"sur_id": "1",
"user_id": "admin#gmail.com",
"pagename": "question_response"
},
{
"name": "check-box[]",
"value": "1"
},
{
"name": "radio",
"value": "radio 2"
},
{
"name": "yes",
"value": "no"
}
]
"ques":[
{
"name": "date",
"value": "2015-10-23"
"user_id": "admin1#gmail.com",
},
{
"name": "select-deopdown",
"value": ""
},
{
"name": "true",
"value": "false"
},
{
"name": "number",
"value": "55"
}
]
}
]
I want to separate the name,value and user_id from the 'ques' array:
while ($fetch = mysql_fetch_array($query1)) {
$content = $fetch['CONTENT_VALUES'];
// print_r($content);
$content_value= mb_convert_encoding($content ,"UTF-8");
$datas = json_decode($content, true);
foreach($datas->ques as $values)
{
echo $values->value . "\n";
print_r($values);
}
$test[] = array('ques' => $datas ,'answer'=>$values);
}

If you want to make three different array for each value then create three blank array and then storing corresponding values into them in foreach . Am giving you a common example below
$name = array();
$values= array();
$users = array();
foreach($datas->ques as $values) {
$name[] = $values->name;
$values[] = $values->value;
$users[] = !empty($values->user_id) ? $values->user_id : '';
}
and further you can modify according your need.
Thank you.

This could help
$data = json_decode($json);
$result = [];
foreach($data as $row)
{
foreach($row as $k => $v)
{
$i = 0;
foreach($v as $key => $val)
{
foreach($val as $k1 => $v1)
{
$result[$i][$k1] = $v1;
}
$i++;
}
}
}
echo json_encode($result);

foreach($datas->ques as $values)
{
$name = $values['name'];
$value = $values['value'];
$user_id = $values['user_id'];
}

I solved this by following code.Thanks for 3 of them to guide by giving ideas.
$datas = json_decode($content, true);
foreach($datas as $values)
{
$name = $values['name'];
$value = $values['value'];
$user_id = $values['user_id'];
$test[]= array('user'=>$user,'name'=>$name,'value'=>$value);
}
}

Related

create tree view like json from existing combined array

I have one combined array of order and its items combined into one array but i am trying to create json structure like order then its items list like wise.
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Output should be like
[
"0":[
{
"OrderNo": "1",
"partycode": "10",
"OrderDetails": [
{
"Item": "abc",
"price": 250
},
{
"Item": "xyz",
"price": 250
}
]
}
],
"1":[
{
"OrderNo": "2",
"partycode": "20",
"OrderDetails": [
{
"Item": "pqr",
"price": 250
},
{
"Item": "lmn",
"price": 250
}
]
}
]
]
This is What i Tried
$mainarray = array();
$orderarray = array();
$orderitemarray = array();
if (count(combinedarray) > 0) {
foreach (combinedarray as $obj) {
$orderarray[] = array("orderid" => $obj->orderid);
$orderitemarray[] = array("Item" => $obj->Item, "price" => $obj->price);
}
}
$mainarray[] = array_unique($orderarray);
$mainarray['OrderDetails'] = $orderitemarray;
echo json_encode($mainarray);
$mainarray = array();
foreach ($combinedarray as $x) {
$id = $x['orderid'];
unset($x['orderid']);
if (! isset($mainarray[$id])) {
$mainarray[$id]['OrderNo'] = $id;
}
$mainarray[$id]["OrderDetails"][] = $x;
}
// Now $mainarray has indexes equal to OrderNo. To count it from zero, use array_values
echo json_encode(array_values($mainarray), JSON_PRETTY_PRINT);
demo
By your given array
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Here is my solution for this
$new = array();
foreach($combinedarray as $r){
$new[$r['orderid']]['orderid'] = $r['orderid'];
$new[$r['orderid']]['partycode'] = $r['partycode'];
$new[$r['orderid']][] = array("item"=>$r['item'],"price"=>$r['price']);
}
$json = json_encode($new);
echo '<pre>';print_r($new);
echo $json;

JSON giving weird output in php

I'm learning php as well as JSON and can't figure out why I have following output:
JSON RESULT:
{
"Results": [
{
"user_id": "1"
},
{
"email": "user#example.com"
},
{
"first_name": "User"
},
{
"last_name": "One"
},
{
"password": "pass1"
},
{
"creation_date": null
},
{
"profile_type": "0"
},
{
"user_id": "2"
},
{
"email": "user2#example.com"
},
{
"first_name": "User"
},
{
"last_name": "Two"
},
{
"password": "pass2"
},
{
"creation_date": null
},
{
"profile_type": "0"
}
]
}
PHP:
<?php
require_once 'config/db.php';
$sql = new db();
$conn = $sql->connect();
$query = isset($_GET['query']) ? mysql_real_escape_string($_GET['query']) : "";
if(!empty($query))
{
$qur = mysql_query($query);
$result = array();
while($r = mysql_fetch_assoc($qur))
{
extract($r);
foreach($r as $key => $value)
{
$result[] = array($key => $value);
}
$json = array("Results" => $result);
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json, JSON_PRETTY_PRINT);
?>
My question is, why does it split each value into new record, I want each MySQL record to be one JSON record.
Just assign your row to $result:
while($r = mysql_fetch_assoc($qur))
{
$result[] = $r;
}
$json = array("Results" => $result);
It's doing this because of your for loop:
foreach($r as $key => $value)
{
$result[] = array($key => $value);
}
Maybe you should try something like json_encode on the data returned.
http://php.net/manual/en/function.json-encode.php
EDIT:
Try something like this:
$data = array();
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
echo json_encode($data, JSON_PRETTY_PRINT);
I wouldn't use mysql to start with, use PDO. But if you must, you don't need foreach. Below will do.
while($r = mysqli_fetch_assoc($qur))
{
$result[] = $r;
$json = array("Results" => $result);
}

Access variable Array Data PHP

i have the following Array Structure from Facebook Graph API response.
"data": [
{
"actions": [
{
"action_type": "comment",
"value": "2"
},
{
"action_type": "offsite_conversion",
"value": "1606"
}
],
"date_start": "2017-04-03",
"date_stop": "2017-05-02"
},
{
"actions": [
{
"action_type": "post",
"value": "2"
},
{
"action_type": "post_reaction",
"value": "33"
},
{
"action_type": "page_engagement",
"value": "816"
},
{
"action_type": "post_engagement",
"value": "807"
},
{
"action_type": "offsite_conversion",
"value": "1523"
}
],
"date_start": "2017-04-03",
"date_stop": "2017-05-02"
},
]
The Number of values is flexible and i want to get the value from "offsite_conversion". Normally i would do it for example like that:
data['data'][0]['actions']['1']['value']
But in that case this doesn't work because ['1'] is variable.
Use a loop and test the action type.
foreach ($data['data'][0]['actions'] as $action) {
if ($action['action_type'] == 'offsite_conversion') {
$result = $data['value'];
break;
}
}
because "offsite_conversions" is always the last
If $data['data'][0]['actions'][LAST VALUE]['value'] is what you're looking for:
Your idea of counting should work then:
$actions = $data['data'][0]['actions'];
$index = count($actions) - 1;
$value = $actions[$index]['value'];
So not completely clear what are you trying to achieve, but in a simple way you can just iterate over your $data array:
$needed_values = array();
foreach ($data['data'] as $item) {
foreach ($item['actions'] as $action) {
if ($action['action_type'] == 'offsite_conversion') {
$needed_values[] = $action['value'];
}
}
}
Barmar has the best approach if you don't know where it is, but it's much easier if you want the last one:
$result = end($data['data'][0]['actions'])['value'];
Pretend $json holds the data from facebook
<?php
$data = json_decode($json);
$conversions = 0;
foreach ($data as $datum) {
foreach ($datum['actions'] as $action) {
if ($action['action_type'] === 'offsite_convserion') {
$conversions += (int)$action['value'];
break;
}
}
}

Search in array in json file

I have an array which has a key with multiple content. I want to get that array which includes the key that I search .
$arr = json_decode('{"people":[
{
"id": "8080",
"content": "foo",
"member": [123, 456],
"interval": 7
},
{
"id": "8097",
"content": "bar",
"member": [1234, 4567],
"interval": 7
}
]}', true);
$results = array_filter($arr['people'], function($people) {
return $people['id'] == 8080;
});
echo json_encode($results);
This will return:
{"id":"8080","content":"foo","member":[123,456],"interval":7}
I want that:
$results = array_filter($arr['people'], function($people) {
return $people['member'] == 123;
});
And this does not work.
Have somebody an idea?
As #JonStirling said in comment. Use in_array() function.
$arr = json_decode('{"people":[
{
"id": "8080",
"content": "foo",
"member": [123, 456],
"interval": 7
},
{
"id": "8097",
"content": "bar",
"member": [1234, 4567],
"interval": 7
}
]}', true);
$searchId = 123;
$results = array_filter($arr['people'], function($people) use ($searchId) {
return in_array($searchId, $people['member']);
});
echo json_encode($results);
Result:
[{"id":"8080","content":"foo","member":[123,456],"interval":7}]
See if this helps:
$arr = json_decode('{"people":[
{
"id": "8080",
"content": "foo",
"member": [123, 456],
"interval": 7
},
{
"id": "8097",
"content": "bar",
"member": [1234, 4567],
"interval": 7
}
]}', true);
$results = array_filter($arr['people'], function($people) {
for($i=0; $i<count($people['member']); $i++){
return $people['member'][$i] == 123;
}
});
echo json_encode($results);
The out come will be:
[{"id":"8080","content":"foo","member":[123,456],"interval":7}]
If you want to do it withouth 'array_filter' you can try this:
function search($arr, $id, $arrayValue)
{
$people = null;
foreach ($arr['people'] as $a)
{
if ($a['id'] == $id)
{
$people = $a;
}
}
$arrayWeAreLookingFor = null;
foreach ($people as $property => $value)
{
if (is_array($value))
{
foreach ($value as $v)
{
if ($v == $arrayValue)
{
$arrayWeAreLookingFor = $people[$property];
}
}
}
}
return $arrayWeAreLookingFor;
}
var_dump(search($arr, 8080, 123));

merge arrays with same value of key

I use php glob function for get images in sub directories and I dont know how many files exist in each directory
directory name is id and I want to categorize all images in directories in one array
$arr = [];
$dir = dirname(__FILE__)."/gulets";
$files = glob($dir."/*/*_gulet_o_*");
foreach ($files as $file) {
$fullname = str_replace($dir."/", "", $file);
$name = explode("/", $fullname);
$name1 = array('id'=>$name[0],'name'=>$name[1]);
$arr[] = $name1;
}
header('Content-Type: application/json');
echo json_encode($arr);
[
{
"id": "10",
"name": "asdsad_gulet_o_1.jpg"
},
{
"id": "10",
"name": "wqes_gulet_o_10.jpg"
},
{
"id": "10",
"name": "qwsdf_gulet_o_11.jpg"
},
{
"id": "10",
"name": "sdce_gulet_o_12.jpg"
},
{
"id": "11",
"name": "fsdsc_gulet_o_13.jpg"
},
{
"id": "11",
"name": "drfvc_gulet_o_14.jpg"
},
{
"id": "12",
"name": "dsyjhk_gulet_o_15.jpg"
},
.
.
and I need change it like this :
[
{
"id": "10",
"name1": "asdsad_gulet_o_1.jpg",
"name2": "wqes_gulet_o_10.jpg",
"name3": "qwsdf_gulet_o_11.jpg"
"name4": "sdce_gulet_o_12.jpg"
},
{
"id": "11",
"name1": "fsdsc_gulet_o_13.jpg"
"name2": "drfvc_gulet_o_14.jpg"
},
{
"id": "12",
"name1": "dsyjhk_gulet_o_15.jpg"
.
.
you want something like this:
foreach ($arr as $a) {
$new_arr[$a['id']]['names'][] = $a['name'];
}
I think creating indexes like name1, name2, name3 etc is not useful. You should create subarray with index names and there put your names. Try code like this:
<?php
$array = array(
array('id'=>1, 'name'=>'qwerty'),
array('id'=>2, 'name'=>'asdf'),
array('id'=>2, 'name'=>'hjkl'),
array('id'=>1, 'name'=>'cvbnm'),
array('id'=>1, 'name'=>'yuiop'),
);
$groups = array();
foreach($array as $singleRow)
{
if(!isset($groups[$singleRow['id']]))
$groups[$singleRow['id']] = array('id'=>$singleRow['id'], 'names'=>array());
$groups[$singleRow['id']]['names'][] = $singleRow['name'];
}
$json = json_encode(array_values($groups));
var_dump($json);
It outputs:
[{"id":1,"names":["qwerty","cvbnm","yuiop"]},{"id":2,"names":["asdf","hjkl"]}]
instead of -
$name1 = array('id'=>$name[0],'name'=>$name[1]);
$arr[] = $name1;
you can use something like -
$nameKey = 'name' . $name[0];
$name1 = array('id'=>$name[0],$nameKey =>$name[1]);
if (!empty($arr[$name[0]])) {
$arr[$name[0]] = $arr[$name[0]] + $name1;
}
else {
$arr[$name[0]] = $name1;
}
and after end of foreach() loop do -
$arr = array_values($arr);

Categories