This is my request:
https://localhost/profiles?id=1,2
i want to have an output of this:
"data": [
{
"id": 1
},
{
"id": 2
}
]
You can do it like below:-
$data = explode(',', $_GET['id']);
$data =array_map(function($item){
return ['id' => $item];
},$data);
echo json_encode(['data' => $data]);
https://eval.in/896004
Try this :-
$data = array('data' => array());
foreach(explode(',', $_GET['id']) as $key => $val){
$data['data'][$key]['id'] = $val;
}
print_r(json_encode($data));
You can do that in more laravel way as well for more cleaner solution.
$data = explode(',', $request->input('id'));
$data = collect($data)->map(function($item){
return ['id' => $item];
});
dd(json_encode(['data' => $data]));
In this particular simple case, you can also do with with preg_replace:
printf('{"data":[%s]}', preg_replace('~(\d+)~', '{"id"=$1}', $_GET['id']));
Related
The code that I have does not display what I need, tell me what I'm doing wrong
$new_array =[];
foreach($result as $row)
{
$array =[
'id'=> $row["id"],
'summ' => $row["summ"],
];
foreach($array AS $key => $val) {
$new_array[] = $val;
}
}
echo json_encode($new_array);
Outputs the following result
["26","180","25","35","24","50","23","50","22","100"]
But I need the result to be different, and I can't.
Here's an example of how it should be:
[
{"26","180"},
{"25","35"},
{"24","50"},
{"23","50"},
{"22","100"}
]
Please tell me how to achieve this?
check this :
foreach($result as $row)
$array[] = ['id'=>$row["id"], 'summ'=>$row["summ"]];
echo json_encode($array);
for example if your $result contains such a array :
$result = [['id'=>1, 'summ'=>2] , ['id'=>3, 'summ'=>4] , ['id'=>5, 'summ'=>6]];
the scripts output will be :
[
{"id":1,"summ":2},
{"id":3,"summ":4},
{"id":5,"summ":6}
]
You can skip the inner loop:
$new_array = [];
foreach($result as $row)
{
$new_array[] = [
$row['id'],
$row['summ']
];
}
echo json_encode($new_array);
That should give you the result:
[
["26","180"],
["25","35"],
...
]
Beside other answer,
I usually use array_map for this kind of array transformation.
$result = [['id' => 1, 'summ' => 2], ['id' => 3, 'summ' => 4], ['id' => 5, 'summ' => 6]];
$output = array_map(function ($item) {
return [$item['id'], $item['summ']];
}, $result);
I am trying to get results when converting a url to json. I thank those who can help me, thank you.
I have this string: id_user123=123;456;789&id_user456=333;545;908
I would like to get this result:
{"result": [
{"id_user123":[ "123", "456", "789" ] },
{"id_user456":[ "333", "545", "908" ] }
]}
Use parse_url to get the "query" part of your string
and parse_str to get each parameter and values.
<?php
$url = 'test.php?id_user123=123;456;789&id_user456=333;545;908';
parse_str(parse_url($url, PHP_URL_QUERY), $queryArray);
$result = [];
foreach ($queryArray as $userId => $values) {
$result['result'][] = [
$userId => explode(';', $values)
];
}
echo "<pre>";
echo json_encode($result, JSON_PRETTY_PRINT);
echo "</pre>";
will output
{
"result": [
{
"id_user123": [
"123",
"456",
"789"
]
},
{
"id_user456": [
"333",
"545",
"908"
]
}
]
}
Simple loop with explode():
$result = ['result' => []];
foreach ($_GET as $userId => $values) {
$result[] = [
$userId => explode(';', $values);
];
}
echo json_encode($result);
I have this ff. assoc array
$array = [
'school' => [
'college' => [
'nursing' => ['n1a', 'n2a', 'n3a', 'n4a'],
'hrm' => ['h1a', 'h2a', 'h3a', 'h4a'],
'tourism' => ['t1a', 't2a', 't3a', 't4a'],
'it' => ['i1a', 'i2a', 'i3a', 'i4a'],
],
'senior' => [],
],
'business' => [
'office' => [
'dep1' => ['team1', 'team2'],
'dep2' => ['team1', 'team2'],
'dep3' => ['team1', 'team2'],
'dep4' => ['team1', 'team2'],
],
],
]
And I have this code, but this only search first level array.
function searchItemsByKey($array, $key) {
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && key($array)==$key){
$results[] = $array[$key];
}
foreach ($array as $sub_array){
$results = array_merge($results, $this->searchItemsByKey($sub_array, $key));
}
}
return $results;
}
All I want is to search all keys in this array that will result all arrays associated with keys like:
searchItemsByKey($array, 'hrm');
That will return:
['h1a', 'h2a', 'h3a', 'h4a']
Thanks.
You can use array_walk_recursive,
$result = [];
$search = "hrm";
function searchItemsByKey($array, $key)
{
$retArr = [];
if (is_array($array)) {
if (!empty($array[$key])) {
return $array[$key];
}
foreach ($array as $val) {
$retArr = array_merge($retArr, searchItemsByKey($val, $key));
}
}
return $retArr;
}
$temp = searchItemsByKey($array, 'hrm');
Demo.
I'm trying to generate the following JSON data:
[
{
"ID": "A1000",
"name": "John Simpson",
"serialID": "S41234",
"tagID": "ABC6456"
},
{
"ID": "B2000",
"name": "Sally Smith",
"serialID": "B5134536",
"tagID": "KJJ451345"
},
{
"ID": "A9854",
"name": "Henry Jones",
"serialID": "KY4239582309",
"tagID": "HYG452435"
}
]
from within a PHP foreach loop which looks like this:
foreach($records as $record) {
$ID = $record->getField('propertyID');
$name = $record->getField('assignedName');
$serialID = $record->getField('serial');
$tagID = $record->getField('tag');
}
I've tried using:
$arr = array('ID' => $ID, 'name' => $name, 'serialID' => $serialID, 'tagID' => $tagID);
which works for each record within the loop, but can't work out the syntax to join them together into a single JSON data string?
Problem:- Your are over-writing your $arr variable each-time inside foreach() loop.That cause the issue.
Solution:- Instead of over-writing, assign values to array like below:-
$arr = []; //create empty array
foreach($records as $record) {
$arr[] = array(
'ID' => $record->getField('propertyID');
'name' => $record->getField('assignedName');
'serialID' => $record->getField('serial');
'tagID' => $record->getField('tag')
);//assign each sub-array to the newly created array
}
echo json_encode($arr);
Add records to some kind of aggregation array and then json_encode it:
$items = [];
foreach($records as $record) {
$items[] = [
'ID' => $record->getField('propertyID'),
'name' = $record->getField('assignedName'),
'serialID' => $record->getField('serial'),
'tagID' => $record->getField('tag'),
];
}
echo json_encode($items);
Try this:
$data= array();
foreach($records as $record) {
$data[] = array(
'ID' => $record->getField('propertyID');
'name' => $record->getField('assignedName');
'serialID' => $record->getField('serial');
'tagID' => $record->getField('tag')
);
}
echo json_encode($data);
Explanation: Make an array, put all the values on one of their numerical index with in the loop, json_enccode() it.
<?php
$ArrayName = array();
foreach($records as $record) {
$ID = $record->getField('propertyID');
$name = $record->getField('assignedName');
$serialID = $record->getField('serial');
$tagID = $record->getField('tag');
$ArrayName[] = array('ID' => $ID, 'name' => $name, 'serialID' => $serialID, 'tagID' => $tagID); //assign each sub-array to the newly created array
}
echo json_encode($ArrayName);
?
> Blockquote
You could use something like array_map() for this:
$result = array_map(function ($record) {
return [
'ID' => $record->getField('propertyID'),
'name' => $record->getField('assignedName'),
'serialID' => $record->getField('serial'),
'tagID' => $record->getField('tag'),
];
}, $records);
echo json_encode($result);
this code will help you:
<?php
$resultArray = array();
foreach($records as $record)
{
$newResultArrayItem = array();
$newResultArrayItem['ID'] = $record->getField('propertyID');
$newResultArrayItem['name'] = $record->getField('assignedName');
$newResultArrayItem['serialID'] = $record->getField('serial');
$newResultArrayItem['tagID'] = $record->getField('tag');
$resultArray[] = $newResultArrayItem;
}
$encodedArray = json_encode($ArrayName);
echo $encodedArray;
?>
When a form gets posted, I get some checkbox values like the below:
Array ( [chk0] => true ,
[chk1] => true,
[chk3] => true,
[chk1002] => on,
[chk1005] => on
)
Using PHP,How can I construct a JSON request like this by using the above variables?
"data":
[
{
"checkboxval": true,
"id": 0
},
{
"checkboxval": true,
"id": 1
},
{
"checkboxval": true,
"id": 3
},
{
"checkboxval": true,
"id": 1002
},
{
"checkboxval": true,
"id": 1005
}
]
Please note that my POST variables can have other form variables too, but all checkbox values will be named with the prefix "chk"
$output = array();
foreach ($input as $k => $v) {
$output[] = array(
'checkboxval' => !!$v,
'id' => preg_replace('!^chk!', '', $k),
);
}
header('Content-Type: application/json');
echo json_encode(array('data' => $output));
foreach ($_POST as $k => $v) {
$output[] = array(
'checkboxval' => ($v=='on'? true : ($v=='off' ? false : !!$v)),
'id' => preg_replace('!^chk!', '', $k),
);
}
header('Content-Type: application/json');
echo json_encode(array('data' => $output));
Credits to cletus who provided the basis for this code.
Have a look at the json_encode() php function. You'll have to massage your array a little to get the exact JSON format you're after.
Heres an example...
$_POST["chk1"] = "Hello";
$_POST["chk2"] = "World";
$jsonArray = array();
foreach($_POST as $key => $val){
if(preg_match("/chk/", $key)){
$jsonArray[$key] = $val;
}
}
$jsonArray = array("Data" => $jsonArray);
$json = json_encode($jsonArray);
echo "<pre>";
echo $json;
echo "</pre>";
Outputs this:
{"Data":{"chk1":"Hello","chk2":"World"}}
I haven't tested this yet, but maybe something like this:
$json = '"data": [';
$first = true;
foreach ($_POST as $k => $v){
if (preg_match('/^chk(\d+)$/', $k, $m)){
if ($first) $first = false; else $json .= ", ";
$json .= sprintf('{ "checkboxval" : %s, "id" : %s }', ($v && $v != "off") ? "true" : "false", $m[1]);
}
}
$json .= ']';