creating JSON from while loop and foreach loop in php - php

I am revamping an application that is using PHP on the serverside which outputs JSON format.
{"by":"Industrie LLC","dead":false,"descendants":396,"id":"396","kids":[1,396],"score":396,"time":"396","title":"Industrie LLC","type":"comment","url":"www.nytimes.com"}
as it is i am getting the last column of mysql data.i know it is something with the loops but i have no idea what in specific.
My PHP code is here
$sql_metro_company_doc_legal = "SELECT * FROM ".$configValues['CONFIG_DB_TBL_PRE']."posts where post_type='company'";
$res_metro_company_doc_legal = $dbSocket->query($sql_metro_company_doc_legal);
while($row_metro_company_doc_legal = $res_metro_company_doc_legal->fetchRow()) {
$notice2[] = $row_metro_company_doc_legal[5];
$notice8[] = strtotime($row_metro_company_doc_legal[0]);
$notice9[] = $row_metro_company_doc_legal[0];
$notice3[] = $row_metro_company_doc_legal[0];
$notice = array("id" => "".$row_metro_company_doc_legal[1]."","title"=>"".$row_metro_company_doc_legal[0]."");
$notice10[] = $row_metro_company_doc_legal[0];
$notice6[] = $row_metro_company_doc_legal[0];
$notice11[] = $row_metro_company_doc_legal[5];
$notice7[] = strtotime($row_metro_company_doc_legal[2]);
$notice12[] = 'www.nytimes.com';
$notice7[] = "comment";
}
foreach ($notice2 as $status2) {
$_page['by'] = $status2;
}
foreach ($notice8 as $status8) {
$_page['dead'] = $status8;
}
foreach ($notice9 as $status9) {
$_page['descendants'] = (int)$status9;
}
foreach ($notice3 as $status3) {
$_page['id'] = $status3;
}
foreach ($notice as $status) {
$_page['kids'][] = (int)$status;
}
foreach ($notice10 as $status10) {
$_page['score'] = (int)$status10;
}
foreach ($notice6 as $status6) {
$_page['time'] = $status6;
}
foreach ($notice11 as $status11) {
$_page['title'] = $status11;
}
foreach ($notice7 as $status7) {
$_page['type'] = $status7;
}
foreach ($notice12 as $status12) {
$_page['url'] = $status12;
}
foreach ($notice4 as $status4) {
$_page['parent'] = (int)$status4;
}
foreach ($notice5 as $status5) {
$_page['text'] = $status5;
}
//sets the response format type
header("Content-Type: application/json");
//converts any PHP type to JSON string
echo json_encode($_page);

You need to make a 2-dimensional array in $_page.
$_page = array();
foreach ($notice2 as $i => $status) {
$_page[] = array(
'by' => $status,
'dead' => $status8[$i],
'descendants' => (int)$status9[$i],
'id' => $status3[$i],
// and so on for the rest
);
}
header ("Content-type: application/json");
echo json_encode($_page);

Related

student distribute in exam hall using codeigniter

I have three table for student first one is roll_no
second is center details
third is rooms details
$anil = array();
$exam_no_students = array();
$session_usr['user']= $this->session->userdata('user_name');
$total_students['total_stu']=$this->DBfunction->totalCountAll('roll_no');
$exam_centers['no_of_centers']= $this->DBfunction->count_centers();
$exam_centers1= $this->DBfunction->count_centers();
foreach ($exam_centers1 as $center_code => $center_details){
$center_code = array('center_id' =>$center_details->center_id);
$center_table='exam_center';
$center_full_details =$this->DBfunction->getArrayWhereResult($center_table,$center_code);
foreach ($center_full_details as $full => $full_de) {
$fullstudent = array('center_f_id' =>$full_de->center_id,
'center_f_name' =>$full_de->exam_center,
'center_f_addres' =>$full_de->exam_center_address ,
'center_f_city' =>$full_de->village ,
'center_f_count' =>$center_details->count);
}
array_push($exam_no_students, $fullstudent);
$center_f_details =$this->DBfunction->getArrayWhereResult($center_table,$center_code);
foreach ($center_f_details as $roomss => $rooms) {
$room_id = array('exam_center_id' =>$rooms->id);
$center_rooms =$this->DBfunction->getArrayWhereResult('exam_center_rooms',$room_id);
foreach ($center_rooms as $rooms_c => $roomsdetails) {
$center_with_rooms['anil'] = array('center_id'=>$rooms->center_id,
'center_name'=>$rooms->exam_center,
'center_main'=>$roomsdetails->exam_center_id,
'no_of_students'=>$center_details->count,
'room_no'=>$roomsdetails->room_no,
'no_of_seating'=>$roomsdetails->noofseating, 'noofrow'=>$roomsdetails->noofrow,
'noofcol'=>$roomsdetails->noofcol
);
}
}
I want to assign student into rooms for exam like below table
i am so confused to do this.
I got solution for above mentioned query using array_slice(). and get desired result.
public function Student_shift(){
$stateus='Approved';
$statuss = array('status' =>$stateus);
$table ='exam_center';
$get_centers=$this->DBfunction->getArrayWhereResult($table,$statuss);
$new_array = array();
foreach ($get_centers as $centers => $centers_name){
$i=1;
$centerid=$centers_name->center_id;
$main_id = $centers_name->id;
$center_where = array('center_id' =>$centerid);
$roll_table='roll_no';
$all_center_student = $this->DBfunction->getArrayWhereResult($roll_table,$center_where);
$all_center_student_count=count($all_center_student);//die;
$rooms_where = array('exam_center_id' =>$main_id);
$room_table= 'exam_center_rooms';
$rooms_details= $this->DBfunction->getArrayWhereResult($room_table, $rooms_where);
$cout = count($all_center_student);
$diff_diff=$all_center_student;
$start =0;
$shift=1;
$rooms_seating = 0;
while ($diff_diff){
$start =0;
$rooms_seating = 0;
$i=0;
ini_set('max_execution_time', 0);
ini_set('memory_limit','2048M');
foreach ($rooms_details as $roo => $rooms_ava){
$sliced_array = array_slice($diff_diff, $start, $rooms_ava->noofseating-2);
$start = $rooms_ava->noofseating-2;
foreach ($sliced_array as $key1 => $all) {
$students_with_rooms = array('enrollment' =>$all->enrollment,
'center_id' =>$all->center_id,
'roll_no' =>$all->roll_no,
'stu_class' =>$all->stu_class,
'room_no' =>$rooms_ava->room_no,
'shift_id'=>$shift
);
$roll_where = array('roll_no' => $all->roll_no);
$table='roll_no';
$data = array('room_no' => $rooms_ava->room_no,
'shift_id'=>$shift
);
$this->DBfunction->updateArrayWhereResult($table, $roll_where, $data);
array_push($new_array, $students_with_rooms);
}
$rooms_seating = $rooms_seating+$rooms_ava->noofseating-2;
$i++;
}
$diff_diff = array_slice($diff_diff, $rooms_seating);
$shift++;
}
}
redirect('Admin/abcd');
}

Magento get Layered Filter from Collection Programmatically

I am building custom webservices for the Mobile app,
I want to load filter according to product collection programmatically.
Currently i am getting filter on entire category but when we apply any filter it will gave same filter option again.
Below is the code which i have used for category filter
$layer = Mage::getModel("catalog/layer");
$_category = Mage::getModel("catalog/category")->load($category_id);
$layer->setCurrentCategory($_category);
$attributes = $layer->getFilterableAttributes();
/* custom for filters
$collection = Mage::getResourceModel('catalog/product_attribute_collection');
$collection->setItemObjectClass('catalog/resource_eav_attribute');
$collection->setAttributeSetFilter(array(4));
$collection->addStoreLabel(Mage::app()->getStore()->getId());
$collection->setOrder('position', 'ASC');
$collection->addFieldToFilter('additional_table.is_filterable', array('gt' => 0));
$attributes = $collection->load();
*/
// print_r($attributes->getData());exit();
$attributeCollection =array();
$i=0;
$attributeCollection = array();
foreach ($attributes as $attribute) {
if($attribute->getAttributeCode() == 'price') {
$filterBlockName = 'catalog/layer_filter_price';
}elseif($attribute->getBackendType() == 'decimal'){
$filterBlockName = 'catalog/layer_filter_decimal';
}else{
$filterBlockName = 'catalog/layer_filter_attribute';
}
$result = Mage::app()->getLayout()->createBlock($filterBlockName)->setLayer($layer)->setAttributeModel($attribute)->init();
$attributeCollection[$i]['Code'] = $attribute->getAttributeCode();
$attributeCollection[$i]['Label'] = $attribute->getStoreLabel();
$j=0;
$attributeOptionCollection =array();
foreach($result->getItems() as $option) {
if($attribute->getAttributeCode()=='price'){
$attributeOptionCollection[$j]['Label'] = strip_tags($option->getLabel());
}else{
$attributeOptionCollection[$j]['Label'] = $option->getLabel();
}
$attributeOptionCollection[$j]['Value'] = $option->getValue();
$attributeOptionCollection[$j]['Type'] = $option->getFrontend();
$j++;
}
$attributeCollection[$i]['Options'] = $attributeOptionCollection;
$i++;
}
// print_r($attributeCollection);exit();
// echo "<pre>";
$counter = 0;
$availableSortOptions = $_category->getavailablesortbyoptions();
foreach ($availableSortOptions as $key=>$options) {
$optinsList[$counter]['Code'] = $key;
$optinsList[$counter]['Label'] =$options;
$counter++;
// print_r($options);
}
$information['Filters'] = $attributeCollection;
Please suggest how i proceed
I used this for a particular Category - hope this helps
//require necessary files
require_once('../app/Mage.php');
$categoryID = $_POST['categoryID'];
//necessary initialization
Mage::app();
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
try{
$json = array('status' => true);
$json['data'] = array();
$layer = Mage::getModel("catalog/layer");
$category = Mage::getModel("catalog/category")->load($categoryID); // 3rd Category
$layer->setCurrentCategory($category);
$attributes = $layer->getFilterableAttributes();
foreach ($attributes as $attribute) {
$filterBlockName = 'catalog/layer_filter_attribute';
$result = Mage::app()->getLayout()->createBlock($filterBlockName)->setLayer($layer)->setAttributeModel($attribute)->init();
foreach($result->getItems() as $option) {
$count[] = array('attribute_name' => $option->getLabel(),'attribute_value' => $option->getValue());
}
if($count!=null){
$json['data'][] = array('name'=>ucfirst($attribute->getAttributeCode()),'count'=>$count);
}
unset($count);
}
}
catch (Exception $e) {
$json = array('status' => false, 'message' => $e->getMessage());
}
echo json_encode($json);

Decoding mixture of array and stdObject to Database

I am trying to decode a collection of json files to a mysql database and return the decoded values to a datatable for presentation. I have one table called ec2_instances, and want to send to that table an array of values which are located at cfi configuration which works fine. but have now added a new column called aws account id which is on object rather than an array I have updated the model to include the new column but I am struggling
<?php
function from_camel_case($input)
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match)
{
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
$resource_types = array();
$resource_types['AWS::EC2::Instance'] = 'EC2Instance';
$resource_types['AWS::EC2::NetworkInterface'] = 'EC2NetworkInterface';
$resource_types['AWS::EC2::VPC'] = 'VPC';
$resource_types['AWS::EC2::Volume'] = 'Volume';
$resource_types['AWS::EC2::SecurityGroup'] = 'EC2SecurityGroup';
$resource_types['AWS::EC2::Subnet'] = 'Subnet';
$resource_types['AWS::EC2::RouteTable'] = 'RouteTable';
$resource_types['AWS::EC2::EIP'] = 'EIP';
$resource_types['AWS::EC2::NetworkAcl'] = 'NetworkAcl';
$resource_types['AWS::EC2::InternetGateway'] = 'InternetGateway';
$accounts = DB::table('aws_account')->get();
$account_id = array($accounts);
$account_id_exists = array_add($account_id, 'key', 'value');
foreach(glob('../app/views/*.json') as $filename)
{
//echo $filename;
$data = file_get_contents($filename);
if($data!=null)
{
$decoded=json_decode($data,true);
if(isset($decoded["Message"]))
{
//echo "found message<br>";
$message= json_decode($decoded["Message"]);
if(isset($message->configurationItem))
{
// echo"found cfi<br>";
$insert_array = array();
$cfi = $message->configurationItem;
switch ($cfi->configurationItemStatus)
{
case "ResourceDiscovered":
//echo"found Resource Discovered<br>";
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$insert_array[from_camel_case($key)] = $value;
}
}
if (array_key_exists($cfi->awsAccountId,$resource_types))
{
$resource = new $resource_types[$cfi->awsAccountId];
foreach ($cfi->awsAccountId as $key => $value)
{
if (in_array($key,$resource->fields))
{
$insert_array[from_camel_case($key)] = $value;
}
}
$resource->populate($insert_array);
if (!$resource->checkExists())
{
$resource->save();

Create array nested PHP

Hi all' I have a page into PHP where I retrieve XML data from a server and I want to store this data into an array.
This is my code:
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string)$entry2->attributes()->HOTEL_CODE;
$hotel_array2 = array();
$hotel_array2['id'] = $entry2->ID;
$hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME);
$i=0;
foreach($entry2->ROOM_DATA as $room){
$room_array = array();
$room_array['id'] = (string)$room->attributes()->CCHARGES_CODE;
$hotel_array2['rooms'][$i] = array($room_array);
$i++;
}
array_push($hotel_array, $hotel_array2);
}
}
In this mode I have the array hotel_array which all hotel with rooms.
The problem is that: into my XML I can have multiple hotel with same ID (the same hotel) with same information but different rooms.
If I have an hotel that I have already inserted into my hotel_array I don't want to insert a new array inside it but I only want to take its rooms array and insert into the exisiting hotel.
Example now my situation is that:
hotel_array{
[0]{
id = 1,
name = 'test'
rooms{
id = 1
}
}
[0]{
id = 2,
name = 'test2'
rooms{
id = 100
}
}
[0]{
id = 1,
name = 'test'
rooms{
id = 30
}
}
}
I'd like to have this result instead:
hotel_array{
[0]{
id = 1,
name = 'test'
rooms{
[0]{
id = 1
}
[1]{
id = 30
}
}
}
[0]{
id = 2,
name = 'test2'
rooms{
id = 100
}
}
}
How to create an array like this?
Thanks
first thing is it helps to keep the hotel id as the index on hotel_array when your creating it.
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string)$entry2->attributes()->HOTEL_CODE;
$hotel_array2 = array();
$hotel_array2['id'] = $entry2->ID;
$hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME);
$i=0;
foreach($entry2->ROOM_DATA as $room){
$room_array = array();
$room_array['id'] = (string)$room->attributes()->CCHARGES_CODE;
$hotel_array2['rooms'][$i] = array($room_array);
$i++;
}
if (!isset($hotel_array[$hotel_array2['id']])) {
$hotel_array[$hotel_array2['id']] = $hotel_array2;
} else {
$hotel_array[$hotel_array2['id']]['rooms'] = array_merge($hotel_array[$hotel_array2['id']]['rooms'], $hotel_array2['rooms']);
}
}
}
Whilst this is the similar answer to DevZer0 (+1), there is also quite a bit that can be done to simplify your workings... there is no need to use array_merge for one, or be specific about $i within your rooms array.
$hotels = array();
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string) $entry2->attributes()->HOTEL_CODE;
if ( empty($hotels[$id]) ) {
$hotels[$id] = array(
'id' => $id,
'name' => utf8_decode($entry2->HOTEL_NAME),
'rooms' => array(),
);
}
foreach($entry2->ROOM_DATA as $room){
$hotels[$id]['rooms'][] = array(
'id' => (string) $room->attributes()->CCHARGES_CODE;
);
}
}
}
Just in case it helps...
And this :)
$hotel_array = array();
foreach ($xml->DATA as $entry)
{
foreach ($entry->HOTEL_DATA as $entry2)
{
$hotel_code = (string) $entry2->attributes()->HOTEL_CODE;
if (false === isset($hotel_array[$hotel_code]))
{
$hotel = array(
'id' => $entry2->ID,
'code' => $hotel_code,
'name' => utf8_decode($entry2->HOTEL_NAME)
);
foreach($entry2->ROOM_DATA as $room)
{
$hotel['rooms'][] = array(
'id' => (string)$room->attributes()->CCHARGES_CODE,
);
}
$hotel_array[$hotel_code] = $hotel;
}
}
}

dynamic variables from array

I store the field names within an array, in hopes to dynamically create the variables.
I receive a illegal offset type error for the if and else, these two lines:
$data[$tmp_field] = $tmp_field[$id];
$data[$tmp_field] = 0;
I checked the post data and it is posting with the appropriate data, but I am not sure what the problem is.
$student_id stores all the students ids., for example: $student_id = array(8,9,11,23,30,42,55);
function updateStudentInfo() {
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$tmp_field] = 0;
} else {
$data[$tmp_field] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
}
This is the array format I desire:
Array
(
[internet_student] => 1
[non_matriculated_student] => 1
[h_number] => 0
[felony] => 0
[probation] => 1
[dismissed] => 0
)
Added screenshot to give you a visual of the form the data is being posted from
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$field_name] = 0;
} else {
$data[$field_name] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
I am assuming that all these fields are arrays, as otherwise you wouldn't need any loops.
function updateStudentInfo()
{
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
$student_count = count($student_id);
foreach($student_id as $id)
{
$data = array();
foreach($fields as $field)
{
if(array_key_exists($id, $$field))
$data[$field] = ${$field}[$id];
}
}
}
You are trying to use the student id as an array key for the other fields but the HTML form is just a standard indexed array, not keyed to any student data.

Categories