Output key and value in one array row - php

I want to set two fields in one row when outputting my array result like:
{
"key" : "value",
...
}
in my part of code:
$letter = $this->getMyRepository()->findAll();
$result = array();
foreach($letter as $key => $value){
$id = $value->getId();
if(!isset($result[$id])) $result[$id] = array();
$result[$id][] = $value->getKey() . ' ' . $value->getValue();
print_r($value);die;
}
but it returns just Key fields.

Related

How to modifying the data structure of array list as per key value using PHP

I need to modify the data structure of json array list as per some key value using PHP. I am explaining my code below.
<?php
$output=array(
array(
"first_name"=>"robin",
"last_name"=>"sahoo",
"reg_no"=>12,
"paper_code"=>"BA001"
),array(
"first_name"=>"robin",
"last_name"=>"sahoo",
"reg_no"=>12,
"paper_code"=>"BA002"
),array(
"first_name"=>"Rama",
"last_name"=>"Nayidu",
"reg_no"=>13,
"paper_code"=>"BA001"
)
);
//echo json_encode($output);
$result=array();
foreach ($output as $key => $value) {
if (count($result)==0) {
$result[]=array(
"name"=>$value["first_name"].' '.$value['last_name'],
"reg_no"=>$value['reg_no'],
"paper1"=>$value['paper_code'],
"paper2"=>"",
"paper3"=>"",
"paper4"=>""
);
}
}
The output of the input array is given below.
// Output:
[
{
"first_name":"robin",
"last_name":"sahoo",
"reg_no":12,
"paper_code":"BA001"
},
{
"first_name":"robin",
"last_name":"sahoo",
"reg_no":12,
"paper_code":"BA002"
},
{
"first_name":"Rama",
"last_name":"Nayidu",
"reg_no":13,
"paper_code":"BA001"
}
];
The above is my array list. Here I need to modify the all row value by reg_no means if there are multiple rows including same reg_no then those will merge with joining the both name and my expected output should like below.
expected output:
[
{
'name':"robin sahoo",
"reg_no":12,
"paper1":"BA001",
"paper2":"BA002",
"paper3":"",
"paper4":""
},
{
'name':"Rama Nayidu",
"reg_no":13,
"paper1":"BA001",
"paper2":"",
"paper3":"",
"paper4":""
}
]
Here paper1,paper2,paper3,paper4 will be selected serially means suppose same reg_no=12 has first row paper_code= BA001 then it will be paper1=BA001 and second row paper_code=BA002 then it will be paper2=BA002 and so on. Here I am using PHP to map this array.
Try the following, Let me know..
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001"));
//echo json_encode($output);
$result=array();
$temp=array();
if(!empty($output)){
foreach ($output as $key => $value) {
if(isset($temp[$value['reg_no']])){
if(empty($temp[$value['reg_no']]["paper1"]) || $temp[$value['reg_no']]["paper1"] == ""){
$temp[$value['reg_no']]["paper1"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper2"]) || $temp[$value['reg_no']]["paper2"] == ""){
$temp[$value['reg_no']]["paper2"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper3"]) || $temp[$value['reg_no']]["paper3"] == ""){
$temp[$value['reg_no']]["paper3"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper4"]) || $temp[$value['reg_no']]["paper4"] == ""){
$temp[$value['reg_no']]["paper4"] = $value['paper_code'];
}
}else{
$temp[$value['reg_no']] = array("name"=>$value["first_name"].' '.$value['last_name'],"reg_no"=>$value['reg_no'],"paper1"=>$value['paper_code'],"paper2"=>"","paper3"=>"","paper4"=>"");
}
}
}
if(!empty($temp)){
foreach ($temp as $key => $value) {
$result[] = $value;
}
}
This Code May help you
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001"));
//echo json_encode($output);
$result=array();
foreach ($output as $key => $value) {
if (count($result)==0) {
$output[$key]=array("name"=>$value["first_name"].' '.$value['last_name'],"reg_no"=>$value['reg_no'],"paper1"=>$value['paper_code'],"paper2"=>"","paper3"=>"","paper4"=>"");
}
}echo "<pre>";print_r($output);
?>
You can try with this
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'name' => $name,
'reg_no' => $value['reg_no'],
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'];
}
$result = array_values($result); // reindex result array
$result = json_encode($result); // Encode to json format
print_r($result); // print result
This assumes that first_name and last_name is always same for each reg_no

How to extract data from JSON - Laravel & JSON

This is how my json looks like ["Chicken",{"quantity":"1"},"Froggies",{"quantity":"2"},"Fryies",{"quantity":"3"}].
Is there a way that i can get the data out the results like
Chicken : 1, Froggies:2, Fryies:3
I tried to use implode to get this done but i get an error saying array to string conversion,
Below is my code
foreach($request->get('item_id') as $key => $id)
{
$selected_item = Item::all()->where('id',$id);
foreach($selected_food as $select)
{
$food_selected[]= $select->name ;
$food_selected[] = ['quantity' => $request->get('quantity')[$key]];
}
}
$query ="Your items are ".implode(',',$food_selected)."";
Maybe array of objects would be more useful in that situation, which you could get this way:
$arr = [];
foreach ( $request->get('item_id') as $key => $id ) {
$selected_item = Item::all()->where('id', $id);
foreach ( $selected_item as $select ) {// $selected_item or $selected_food here
/*
$obj = new stdClass;
$obj->{$select->name} = $request->get('quantity')[$key];
$arr[] = $obj;*/
$arr[$select->name] = (int) $request->get('quantity')[$key];
}
}
$query = '';
foreach ( $arr as $k => $v ) {
$query .= ' '.$k.': '.$v.',';
}
$query = rtrim($query, ',');
$query = ltrim($query);
$query = "Your items are ".$query;
I assume that the ID is unique key for an Item and your Item::all()->where('id',$id) will return only one record. If this is true, the second loop is unnecessary.
Based on this assumption, I come to this code:
$result = collect($request->get('item_id'))
->map(function($itemId, $itemKey) use ($request) {
$item = Item::find($itemId);
return $item->name . ' : ' . $request->get('quantity')[$itemKey];
})->implode(',');
// $result contains the string: "Chicken : 2, Fries : 1"
For explanation:
Cast the array into a collection
Use map to loop over it
Find the Item by its ID
Return the name and the quantity (this returns a collection)
Implode the collection

Foreach loop $key => $value

$suggestions = array();
$this->db->from('items');
$this->db->where('deleted',0);
$this->db->like('name', $search);
$this->db->limit($limit);
$by_name = $this->db->get();
$temp_suggestions = array();
foreach($by_name->result() as $row)
{
if ($row->category && $row->size)
{
$temp_suggestions[$row->item_id] = $row->name . ' ('.$row->category.', '.$row->size.')'.' Unit Price: '. $row->unit_price;
}
elseif ($row->category)
{
$temp_suggestions[$row->item_id] = $row->name . ' ('.$row->category.')'.' Unit Price: '.$row->unit_price;
}
elseif ($row->size)
{
$temp_suggestions[$row->item_id] = $row->name . ' ('.$row->size.')'.' Unit Price: '.$row->unit_price;
}
else
{
$temp_suggestions[$row->item_id] = $row->name.' Unit Price: '.$row->unit_price;
}
}
asort($temp_suggestions);
foreach($temp_suggestions as $key => $value)
{
$suggestions[]=array('value'=> $key, 'label' => $value); // Please take a look at this line
}
hi please see commented line, that foreach loop only display 2 columns from 9 columns, they are key and value. key contains ID and values display value of Qty column
So the question is:
how to modify this foreach loop to get ALL column of query with foreach loop?
The variable $temp_suggestions contains rows, not columns. To get all the data from each row, you must insert that data into $temp_suggestions in the prior loop. For example, to return all the columns as a comma-separated list indexed by the item_id:
foreach($by_name->result() as $row) {
$temp_suggestions[$row->item_id] = implode(', ', (array) $row);
}

php, mysql, arrays - how to get the row name

I have the following code
while($row = $usafisRSP->fetch_assoc()) {
$id = $row['id'];
$Applicantid = $row['Applicantid'];
$unique_num = $row['unique_num'];
// .................
$hidden_fields = array($Applicantid, $unique_num, $regs_t ....);
$hidden_values = array();
foreach ($hidden_fields as $key => $value) {
$hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
echo $hidden_values[$value];
}
}
and the result is something like this
0 = 116153840
1 = 136676636
2 = 2010-12-17T04:12:37.077
3 = XQ376
4 = MUKANTABANA
I would like to replace 0, 1, 2, 3 etc with some custom values like "Id", "application name" to make the result like
id = 116153840
application name = 136676636
etc ..
how can I do that ?
Replace the $hidden_fields = array(... line with the following:
$hidden_keys = array('id', 'Applicantid', 'unique_num');
$hidden_fields = array_intersect_key($row, array_fill_keys($hidden_keys, NULL));
If you want to suppress all fields with value 0, either use
$hidden_fields = array_filter($hidden_fields, function($v) {return $v != 0;});
(this will completely omit the 0-entries) or
$hidden_fields = array_map($hidden_fields, function($v) {return ($v==0?'':$v);});
(this will leave them blank). If you're using an older version than 5.3, you'll have to replace the anonymous functions with calls to create_function.
I assume not every field in your row should be a hidden field. Otherwise you could just do $hidden_fields = $row.
I would create an array that specifies the hidden fields:
$HIDDEN = array(
'id' => 'Id',
'Applicantid' => 'application name',
'unique_num' => 'whatever'
);
And then in your while loop:
while(($row = $usafisRSP->fetch_assoc())){
$hidden_fields = array();
foreach$($HIDDEN as $field=>$name) {
$hidden_fields[$name] = $row[$field];
}
//...
foreach($hidden_fields as $name => $value) {
$hidden_fields[$name] = $name . ' = ' . base64_decode($value);
echo $hidden_values[$name];
// or just echo $name, ' = ',$hidden_fields[$value];
}
}
foreach ($row as $key => $value) {
$hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
echo $hidden_values[$value];
}
This could give you something relevant. Through accessing the string keys from the row array which contains the string keys

PHP: high depth array, how do return current key name?

I have a huge array from a json_decode result (assoc set to true) and have the following code to check if (one of the arrays within, a random serial) has the key 'set_true'
$out = "";
foreach ($array as $sub) {
//$out[] = $sub['set_true'];
if (in_array($sub['set_true'], $sub) && $sub['set_true'] == '1' ) {
$out[] = 'User: ' . $sub . ' has set_true = 1';
}
}
That code lists all the users with that array key set to 1, but $sub returns 'array' and not the current key I'm on! (the random serial)
How do I return it?
If you are looping through an array with foreach, and want to know the key you're currently on in the loop, you can use this syntax :
foreach ($array as $key => $value) {
// $key contains the name of the current key
// and $value the current value
}
What's up with your in_array call? I don't think that is correct. Why do you look for $sub in $sub?
I think you mean:
$out = "";
foreach ($array as $key => $sub) {
if (array_key_exists('set_true', $sub) && $sub['set_true'] == '1' ) {
$out[] = 'User: ' . $key . ' has set_true = 1';
}
}

Categories