How to form Json array from sql pdo data in php? - php

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);

Related

Find elements with empty value in multidimensional array

I have an array like the below:
$arrays = [
'a' => [
'name' => "Name 1",
'age' => "99",
'add' => ""
],
'b' => [
'name' => "Name 2",
'age' => "99",
'add' => "Add2"
],
'c' => [
'name' => "Name 3",
'age' => "99",
'add' => "Add3"
],
'd' => [
'name' => "",
'age' => "",
'add' => "Add4"
]
];
I want to get a result like:
$res = [
'a' => ['add'],
'd' => ['name','age']
];
I have tried with the below code, but it returns 1.
$status = array_walk_recursive($arrays, function($v, $k) {
global $output;
if (empty($v) && $v !== 0)
$output[$k] = $v;
});
I want to do it without using any loops because my real input array is very large and I am concerned with performance.
If your input is always of a fixed depth, you can map the existing values to the keys of all empty items:
$output = array_map(function($row) {
return array_keys(array_filter($row, function ($e) {
return empty($e) && $e !== 0;
}));
}, $arrays);
The outer function runs for each "row", the value of which is then converted into a list of all keys with empty values (excluding zeroes, as in the question).
This will keep the outer keys B & C as empty arrays, so if you want them to be removed as well then run another iteration of array_filter over the result:
$output = array_filter($output)
See https://3v4l.org/c23ZB
As mentioned in the comments, there are still several loops going on here, they're just not as visible in the code. A regular foreach loop might end up being a lot easier to read, and possibly perform faster as well.
You can use next combination of array_walk & array_filter:
$result = [];
array_walk(
$arrays,
function($el, $key) use(&$result) {
$empty = array_filter($el, function($el){return $el == "";});
$empty_keys = array_keys($empty);
if (count($empty_keys)) $result[$key] = $empty_keys;
}
);
Try it here
This is another way to achieve your desired output.
$result = [];
foreach($arrays as $key => $value) {
$empty_arr = array_filter($value, function ($ele) {
return empty($ele);
});
$empty_arr_keys = array_keys($empty_arr);
if(!empty($empty_arr_keys)) $result[$key] = $empty_arr_keys;
}
print_r($result);
#iainn's answer can be sharpened up by calling !strlen() on the deep values.
Code: (Demo)
var_export(
array_filter(
array_map(
fn($row) => array_keys(
array_filter(
$row,
fn($v) => !strlen($v)
)
),
$array
)
)
);
But you will end up making fewer iterations and writing cleaner, more intuitive/readable code if you use classic loops. This is how I would write it in my own project:
Code: (Demo)
$result = [];
foreach ($array as $rowKey => $row) {
foreach ($row as $key => $value) {
if (!strlen($value)) {
$result[$rowKey][] = $key;
}
}
}
var_export($result);

Convert threeDimensionalArray to Two and save csv

I have problem with convert array. I have structure like as
$threeDimensionalArray = [
[
[
'name' => 'name1',
],
[
'name' => 'name2',
],
],
[
[
'time' => 123,
'anyField'=>22222,
'anyField1'=>22222,
'anyField2'=>22222
],
[
'time' => 457,
'anyField'=>22222,
'anyField1'=>22222,
'anyField2'=>22222
],
],
];
I need convert this array to two dimensional and save each array to csv file via fputscsv
example
first line in CSV
'name1','name2',
second line
123, 457, etc
This solution will help in your specific case:
$to_csv = [];
foreach ($threeDimensionalArray as $first_level) {
foreach ($first_level as $second_level) {
foreach ($second_level as $key => $value) {
$to_csv[$key][] = $value;
}
}
}
$fp = fopen('file.csv', 'w');
foreach ($to_csv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
The idea is to firstly configure array to two layers array with grouping by key and use fputcsv() afterwards.
I resolve this problem :)
foreach ($threeDimensionalArray as $firstDimensional) {
$array= [];
foreach ($firstDimensional as $twoDimensional) {
$array[] = $twoDimensional['name'] ?? null .$twoDimensional['time'] ?? null;
}
fputcsv($fp, $array);
$returnArray[]=$array;
}

How to loop id from url parameter

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']));

PHP JSON Encoding within foreach loop

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;
?>

Build array of keys and values?

Im trying to build a json array in php with this structure:
[{"id":"name last name",
"id":"name last name",
"id":"name last name"
}]
where the id key is always a different number, not only id string
Im trying to do this:
for ($i = 0; $i < count($array); $i++){
//$namesArray[] = array($array[$i]["id"] =>$array[$i]["name"].
// " ".$array[$i]["last"]." ".$array[$i]["name"]);
$namesArray[] = array_fill_keys(
$array[$i]["id"],
$array[$i]["name"]." ".
$array[$i]["last"]." ".
$array[$i]["name"]
);
}
echo json_encode($namesArray);
With the commented lines I get something like this:
[{"id":"name last name"},
{"id":"name last name"}
]
But I dont want that, I want all keys and values in a single array.
Thanks.
Keep your code clean
$array = [];
$array[] = ['id'=>3 , 'name'=>'H', 'last'=>'bensiali' ];
$array[] = ['id'=>4 , 'name'=>'Simon', 'last'=>'Says' ];
$array[] = ['id'=>5 , 'name'=>'Mohammed', 'last'=>'Ali' ];
$val = [];
foreach ($array as $key => $value) {
$val[$value['id']] = sprintf("%s %s" , $value['name'] , $value['last']);
}
echo json_encode($val);
And output will be:
{"3":"H bensiali","4":"Simon Says","5":"Mohammed Ali"}
Here is how you can do it:
// sample data
$array = array(
array("id" => 1, "name" => "James", "last" => "Last"),
array("id" => 2, "name" => "Micheal", "last" => "Jackson"),
);
// create empty object (associative array)
$obj = (object) array();
// add key/value pairs to that object
foreach ($array as $row) {
$obj->$row["id"] = $row["name"] . " " . $row["last"];
}
// wrap object in a single-element array
$result = array($obj);
// output to JSON string
echo json_encode($result, JSON_PRETTY_PRINT);
Output:
[
{
"1": "James Last",
"2": "Micheal Jackson"
}
]
You can use functional approach to fill desired array with array_reduce:
$array = [
['id' => 1, 'name' => 'name1', 'last' => 'last1'],
['id' => 2, 'name' => 'name2', 'last' => 'last2'],
['id' => 3, 'name' => 'name3', 'last' => 'last3'],
];
$newArray = array_reduce($array, function($carry, $item) {
$carry[$item['id']] = $item["name"]." ".
$item["last"]." ".
$item["name"];
return $carry;
});
var_dump($newArray);
And output will be:
array(3) {
[1]=>
string(17) "name1 last1 name1"
[2]=>
string(17) "name2 last2 name2"
[3]=>
string(17) "name3 last3 name3"
}

Categories