Rearrange each key as object into an object of keys - php

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(),
];
}

Related

PHP: group array of objects by id, while suming up object values [duplicate]

This question already has answers here:
How to GROUP BY and SUM PHP Array? [duplicate]
(2 answers)
Closed 9 months ago.
I'm having a hard time manipulating an array of objects in PHP. I need to group the objects by id, while summing up the points.
Starting array of objects:
[
{
"id": "xx",
"points": 25
},
{
"id": "xx",
"points": 40
},
{
"id": "xy",
"points": 40
},
]
What I need:
[
{
"id": "xx",
"points": 65
},
{
"id": "xy",
"points": 40
},
]
As a frontender, I'm having a hard time with object/array manipulations in PHP. Any help would be greatly appreciated!
i hope this answer help you
first i will change objects to array and return the result to array again
$values =[
[
"id"=> "xx",
"points"=> 25
],
[
"id"=> "xx",
"points"=> 40
],
[
"id"=> "xy",
"points"=> 40
],
];
$res = array();
foreach($values as $vals){
if(array_key_exists($vals['id'],$res)){
$res[$vals['id']]['points'] += $vals['points'];
$res[$vals['id']]['id'] = $vals['id'];
}
else{
$res[$vals['id']] = $vals;
}
}
$result = array();
foreach ($res as $item){
$result[] = (object) $item;
}
output enter image description here
Parse JSON as Object
Aggregate Data
Put back as JSON
$json = <<<'_JSON'
[
{
"id": "xx",
"points": 25
},
{
"id": "xx",
"points": 40
},
{
"id": "xy",
"points": 40
}
]
_JSON;
$aggregate = [];
foreach(json_decode($json) as $data) {
if(!isset($aggregate[$data->id])) $aggregate[$data->id] = 0;
$aggregate[$data->id] += $data->points;
}
$output = [];
foreach($aggregate as $id => $points) {
$output[] = ['id' => $id, 'points' => $points];
}
echo json_encode($output);
[{"id":"xx","points":65},{"id":"xy","points":40}]
You may use array_reduce buil-in function to do the job. Also, when looping through the object's array (the callback), you should check if the result array has the current item's ID to verify that wether you need to add the item to the result array or to make the sum of points attributes.
Here's an example:
// a dummy class just to replicate the objects with ID and points attributes
class Dummy
{
public $id;
public $points;
public function __construct($id, $points)
{
$this->id = $id;
$this->points = $points;
}
}
// the array of objects
$arr = [new Dummy('xx', 25), new Dummy('xx', 40), new Dummy('xy', 40)];
// loop through the array
$res = array_reduce($arr, function($carry, $item) {
// holds the index of the object that has the same ID on the resulting array, if it stays NULL means it should add $item to the result array, otherwise calculate the sum of points attributes
$idx = null;
// trying to find the object that has the same id as the current item
foreach($carry as $k => $v)
if($v->id == $item->id) {
$idx = $k;
break;
}
// if nothing found, add $item to the result array, otherwise sum the points attributes
$idx === null ? $carry[] = $item:$carry[$idx]->points += $item->points;
// return the result array for the next iteration
return $carry;
}, []);
This will result in something like this:
array(2) {
[0]=>
object(Dummy)#1 (2) {
["id"]=>
string(2) "xx"
["points"]=>
int(65)
}
[1]=>
object(Dummy)#3 (2) {
["id"]=>
string(2) "xy"
["points"]=>
int(40)
}
}
Hope that helps, feel free to ask for further help.
Let's use a helper variable called $map:
$map = [];
Build your map:
foreach ($input => $item) {
if (!isset($map[$item["id"]])) $map[$item["id"]] = 0;
$map[$item["id"]] += $item["points"];
}
Now let's build the output:
$output = [];
foreach ($map as $key => $value) {
$output[] = (object)["id" => $key, "points" => $value];
}

create embedded json for autocomplete

I am using following code for making data coming from database as json format
public function employeeSearch()
{
$arrayOfEmployee = array();
$arrayToPush = array();
$arrayToJSON = array();
$new_item = $this->apicaller->sendRequest(array(
"controller" => "Employee",
"action" => "employeeSearch",
"searchCriteria" => "12345"
));
$arrayOfEmployee = json_decode($new_item,true);
foreach($arrayOfEmployee as $key => $employee)
{
$arrayToPush = array('data' => $employee['FullName'], 'value' => $employee['_id']['$oid']);
array_push($arrayToJSON, $arrayToPush);
}
echo json_encode($arrayToJSON);
}
The output is
[{"data":"Aasiya Rashid Khan","value":"5aa662b0d2ccda095400022f"},
{"data":"Sana Jeelani Khan","value":"5aa75d8fd2ccda0fa0006187"},
{"data":"Asad Hussain Khan","value":"5aaa51ead2ccda0860002692"},
{"data":"Ayesha Khan Khann","value":"5aab61b4d2ccda0bc400190f"},
{"data":"adhar card name","value":"5aaba0e1d2ccda0bc4001910"}
]
Now I want that json elements should look like
{
"suggestions": [
{
"value": "Guilherand-Granges",
"data": "750"
},
{
"value": "Paris 01",
"data": "750"
}
]
}
I have to implement this in jQuery autocomplete plugin...
Please help!!!
Replace the last line with
echo json_encode(["suggestions" => $arrayToJSON]);
This should result in the wanted result!
(This hold only true if you igonre the fact that the data in value and name is not the same/similar)

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 set the id to each new array in an array of objects?

I have array of objects like this
[
{
"name": "qwe",
"password": "qwe"
},
{
"name": "qwe1",
"password": "qwe1"
}
]
I need add id each pair of "name" and "password", it must be like this
[
{
"name": "qwe",
"password": "qwe"
"id":"0"
},
{
"name": "qwe1",
"password": "qwe1"
"id":"1"
}
]
I'm trying to move an array using foreach
$users[] = array('name' => $name, 'password' => $password);
$i = 0;
foreach ($users as $key => $value, "id" => 0) {
$value['id'] = $i;
$i++;
}
I'm beginner in php, help please.What i do wrong?
When you iterate through an array using: foreach($array as $key => $value), the $value will be a copy of the original object. Changing the copy will have no effect on the original array.
You need to make sure you update the original value. There are two ways you can do this.
Accessing the original array directly:
foreach ($users as $key => $value) {
// Access the original array directly
$users[$key]['id'] = $i;
$i++;
}
Using references (The &-sign):
foreach ($users as $key => &$value) {
// The & will make it a reference to the original value instead of a copy
$value['id'] = $i;
$i++;
}

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.
}
}

Categories