convert php response array as comma separated [duplicate] - php

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I am trying to get facebook friends by using facebook api.
I am getting response
{
"data": [
{
"id": "groupID",
"members": {
"data": [
{
"name": "Abc",
"administrator": false,
"id": "xxxxxx"
},
{
"name": "NewCas",
"administrator": false,
"id": "xxxxxxxxx"
},
{
"name": "Cds",
"administrator": false,
"id": "xxxxxxxxx"
},
{
"name": "akaha",
"administrator": false,
"id": "xxxxxxx"
},
}
}
This is my code
$fql = 'https://graph.facebook.com/me/groups?fields=id,members&access_token='.$access_token.'&limit=3';
$fqlresult = file_get_contents($fql);
$f = json_decode($fqlresult, true);
tried implode.
$result = implode(',', array_column($f['data'], 'id'));
I am getting this response
GroupID,GroupID,GroupID
I want to take response user ids (members id) as
xxxxxx,xxxxxx,xxxxxx,xxxxxx,xxxxxx,xxxxxx,xxxxxx
Thanks

The other answers are almost correct, but the data is an array with one element so it should be:
echo implode(',', array_column($f['data'][0]['members']['data'], 'id'));
and that is when you have only one groupid, if you have multiple group ids you will need to loop trough it. (loop over the [0] by checking $groupcount = count($f['data']);

This works...
$arr = array(
'data' => array(
array('id' => 'xxxx1'),
array('id' => 'xxxx2'),
array('id' => 'xxxx3'),
array('id' => 'xxxx4'),
array('id' => 'xxxx5'),
array('id' => 'xxxx6'),
array('id' => 'xxxx7'),
array('id' => 'xxxx8'),
)
);
echo implode(',', array_column($arr['data'], 'id'));
EDIT - based on your update and change of request...
echo implode(',', array_column($arr['data'][0]['members']['data'], 'id'));
please review http://php.net/manual/en/language.types.array.php and the section on multidimensional arrays

$data_arr=json_decode($data,true);
$return_str="";
foreach($data_arr['data'] as $row)
{
$return_str .=implode(", ", array_column($row['members']['data'], 'id')) ;
}
echo rtrim($return_str,",");
This will work for multiple elements in $f['data'].

echo implode(',', array_column($f['data'][0]['members']['data'], 'id'));

Make sure your PHP version is 5.5+. Below the specified version will not support array_column function. You can also use this code without array_column.
$data = $result['data'][0]['members']['data'];
$keyValue = '';
foreach ($data as $outerKey => $outerValue) {
foreach ($outerValue as $key => $value) {
if($key == 'id'){
$keyValue .= $value . ' ';
}
}
}
echo $keyValue;

Related

PHP merge array by "depth"? [duplicate]

This question already has answers here:
How to array_merge_recursive() an array?
(2 answers)
Closed 3 months ago.
I have an array like this:
[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_1": {
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]
I want output like this:
[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]
The answers that I found offered to search by name("function_1", "function_2"). But this does not suit me, the function will not always pass an array. I need exactly the "depth" or any other reasonable way.
Thank you!
To achieve your desired result, you could json-decode, recursively merge each individual subarray, then loop over that structure to push each item as a second-level array like this: (Demo)
$array = json_decode($json, true);
$merged = array_merge_recursive(...$array);
$result = [];
foreach ($merged as $key => $data) {
$result[] = [$key => $data];
}
var_export($result);
But I can't imagine getting any benefit from adding unnecessary depth to your result array. I recommend simply json decoding, then calling array_merge_recursive() with the spread operator: (Demo)
var_export(
array_merge_recursive(
...json_decode($json, true)
)
);
Output:
array (
'function_1' =>
array (
'element' =>
array (
'error' => '0',
'msg' => 'test',
),
'element_2' =>
array (
'error' => '0',
'msg' => 'test',
),
),
'function_2' =>
array (
'element' =>
array (
'error' => '0',
'msg' => 'test',
),
'element_2' =>
array (
'error' => '0',
'msg' => 'test',
),
),
)
Your data structure looks weird for the purpose you are trying to achieve I'm bored af tho and created this code for you
function combineElementsPerfunction($functions) {
$result = [];
$uniqueFunctions = [];
foreach ($functions as $function) {
$functionName = array_keys($function)[0];
$uniqueFunctions[] = $functionName;
}
$uniqueFunctions = array_unique($uniqueFunctions);
foreach ($uniqueFunctions as $uniqueFunction) {
$functionObjects = array_filter(
$functions,
function($function) use ($uniqueFunction) {
$functionName = array_keys($function)[0];
return $functionName === $uniqueFunction;
}
);
$elements = [];
foreach ($functionObjects as $functionObject) {
$function = array_shift($functionObject);
$elements = array_merge($elements, $function);
}
$result[] = [
$uniqueFunction => $elements
];
}
return $result;
}
function changeArr($data){
$box = $new = [];
foreach ($data as $v){
$key = array_key_first($v);
$i = count($box);
if(in_array($key, $box)){
$keys = array_flip($box);
$i = $keys[$key];
}else{
$box[] = $key;
}
$new[$i][$key] = isset($new[$i][$key]) ? array_merge($new[$i][$key], $v[$key]) : $v[$key];
}
return $new;
}

Rearrange each key as object into an object of keys

So I can't exactly spot what I am doing wrong here, so I'm hoping the community could give me a boost so I can figure out exactly what is causing this.
I have the following foreach where I'm setting a bunch of objects into an array of objects.
$result = [];
foreach($items as $item) {
$result[] = ['id' => $item->get_id()];
$result[] = ['media_type' => $item->get_media_type()];
}
var_dump($result);
With the above code, I am getting the following output on var_dump($result);:
[
{
"id": "17992874035441353"
},
{
"media_type": "CAROUSEL_ALBUM"
},
{
"id": "17842233125750202"
},
{
"media_type": "IMAGE"
}
]
Here is what I am aiming for:
[
{
"id": "17992874035441353",
"media_type": "CAROUSEL_ALBUM"
},
{
"id": "17842233125750202",
"media_type": "IMAGE"
},
]
Could someone spot what might be going on with how I'm formatting the foreach and setting up the new array? I've tried multiple different things and can't seem to figure out the answer.
Every time you do: $result[] = ..., you're pushing a new array element into the array. You need to push all the data as one single array:
foreach($items as $item) {
$result[] = [
'id' => $item->get_id(),
'media_type' => $item->get_media_type(),
];
}

Create 2D-Array from mysql query in php

I have this following result in my query:
I'm trying to create an array like this in php:
[
{
"software_version": "1.0",
"version_date": "10/08/2016",
"changelog": [
{
"type": "IMP",
"description": "Initial version."
}
]
},
{
"software_version": "1.0.1",
"version_date": "27/07/2017",
"changelog": [
{
"type": "ADD",
"description": "HostPanel update manager."
},
{
"type": "ADD",
"description": "Hook OnDaemonMinute."
}
]
}
]
I need to combine the result with the software_version row.
Any help is appreciated.
My php code:
$changelog = array();
foreach ($result as $r) {
$changelog[] = array(
'software_version' => $r['software_version'],
'version_date' => $r['version_date'],
'changelog' => array(
array(
'type' => 'IMP', // help
'description' => 'Initial version.'
)
)
);
}
The key is to use the software version as a key in $changelog as you build it.
$changelog = array();
foreach ($result as $r) {
// get the version (just to make the following code more readable)
$v = $r['software_version'];
// create the initial entry for the version if it doesn't exist yet
if (!isset($changelog[$v]) {
$changelog[$v] = ['software_version' => $v, 'version_date' => $r['version_date']];
}
// create an entry for the type/description pair
$change = ['type' => $r['type'], 'description' => $r['description']];
// add it to the changelog for that version
$changelog[$v]['changelog'][] = $change;
}
You'll need to use array_values to reindex $changelog before JSON encoding it in order to produce the JSON array output you're going for.
$changelog = array_values($changelog);

how to get a value of multidimensional array on php

hi im bulding a site with php that use a json api and i need to echo the values of an multidimensional array
"troopsLevels": [
{
"value": 5,
"globalID": 4000000
},
{
"value": 5,
"globalID": 4000001
},
{
"value": 4,
"globalID": 4000002
},
this is a example of my json file what i need is to show the value "value" knowing depending of the globalID
but not sure how to do it
i was thinking something like
$troop_lvl = $data['troopsLevels'];
if($troop_lvl['globalID'] == 4000000){echo $troop_lvl['value']}
but of curse this will not work as i dont specify the item [0]..[2]
but that actually thats what i need to avoid using [0] to select specific array i need to read all and only show the ['value'] when i give the globalid
i really hope yo can understand me english is not my mother language
thanks a lot for you help
You need to use foreach loop
foreach ($troop_lvl as $key=>$value) {
if($value['globalID'] == 4000000) {
echo $value['value'];
}
}
Use foreach
foreach ($troop_lvl as $key=>$value) {
if($value['globalID'] == 4000000) {
echo $troop_lvl['value'];
}
}
See below:
<?php
$arr = array("test" => array("value" => 1, "value2" => 2), "test2" => array("value" => 21, "value2" => 22));
$encode_arr = json_encode($arr);
$decode_arr = json_decode($encode_arr);
//print_r($decode_arr);
foreach ($decode_arr as $key => $value) {
if($value->value2==2)
echo $value->value;
}
?>
The output will be 1.
This should work for you,
$a = '{"troopsLevels": [
{
"value": 5,
"globalID": 4000000
},
{
"value": 5,
"globalID": 4000001
},
{
"value": 4,
"globalID": 4000002
}
]}';
$abc = json_decode($a);
foreach ($abc->troopsLevels as $row) {
if ($row->globalID == 4000000) {
echo $row->value;// prints value as 5 for the current input.
}
}

PHP array to be the same out to JSON format structure

Here's what I want to do in my php array to be exact json format below:
JSON
{
"suggestions": [
{ "value": "Alex - alex#email.com", "data": {"id": 1, "name": Alex } },
{ "value": "John - john#email.com", "data": {"id": 2, "name": John } },
{ "value": "Diaz - diaz#email.com", "data": {"id": 3, "name": Diaz } }
]
}
Query result in my php array:
array(
0 => array('id'=>'1' 'email'=>'alex#email.com', 'name'=>'Alex'),
1 => array('id'=>'2' 'email'=>'john#email.com', 'name'=>'John'),
2 => array('id'=>'3' 'email'=>'diaz#email.com', 'name'=>'Diaz')
);
Do you have any idea how will you make my php array to that JSON format way?
You can simply use json_encode(); function for that.
json_encode($array);
This should help you for your JSON format
foreach($query as $key => $val){
$json[$key]['value'] = $val['name']." - ".$val['email'];
$json[$key]['data']["id"] = $val['id'];
$json[$key]['data']["name"] = $val['name'];
}
echo json_encode($json);
foreach ($your_array as $key => $val) {
foreach ($val as $k => $v) {
if ($v == 'email') {
//get the value of 'email' key in 'value'
$newArr['suggestions']['value'] = current($v);
}
else {
//if value is not email push it in 'data' key
$newArr['suggestions']['data'] = $v;
}
}
}
//lastly encode the required array
echo json_encode($newArr);

Categories