Show data from 3 tables - php

I have 3 tables, the first one is table name Post, the second is comment, and third is defineComment. I want to show all 3 tables, but my code is too long. Could you please advice me?
$r = $this->w->listwall();
if($r)
{
foreach($r as $key)
{
// load comment to view data
$pc['pc_comment'] = $this->w->get_comments($key['p_id']);
$data['wall'][] = [
'u_id'=>$key['u_id'],
'p_id'=>$key['p_id'],
'u_fname'=>$key['u_fname'],
'u_lname'=>$key['u_lname'],
'p_text'=>$key['p_text'],
'p_date'=>$key['p_date'],
'u_pf' =>$this->pf->getprofile($key['u_id']),
'p_img'=>$this->w->getimg($key['p_id']),
'cover'=>$this->w->getcoverimg($key['p_id']),
'bgpf' =>$this->w->getbgimg($key['p_id']),
'p_link'=>$key['p_link'],
'pc_comment'=>$this->w->get_comments($key['p_id']),
'pc_count'=>$this->w->get_count_comment($key['p_id']),
'pc'=>$this->load->view('wall/v_comment_wall', $pc, TRUE),
'p_like'=>$this->w->get_list_like($key['p_id']),
'count_like'=>$this->w->count_like_post($key['p_id'])
];
}
$data['pf'] = $this->pf->getprofile(uid());
//$data['edittext'] =
//if(count($data) >= 1){
$this->load->view('wall/v_wall',$data);
I also try the code below but It didn't work.
$r = $this->w->listwall();
foreach ($r as $key => $value) {
$data[] = array($key => $value, $this->w->get_comments($value['p_id']));
}

Related

Mongo db cursor count not working properly?

I have written following code in php and am using mongo db as database
$projection = array("broadcast_id" => 1,"studentList" => 1);
$query = array('broadcast_id'=> $broadcast_id);
$count = $this->collection->find($query)->count();
$cursor = $this->collection->find($query,$projection);
$result = array();
foreach($cursor as $row)
{
$idstring = trim($row["studentList"]);
$idstring = preg_replace('/\.$/', '', $idstring);
$idarray = explode('|', $idstring);
foreach($idarray as $studentId)
{
$this->StudentCollection = $this->db->studentTbl;
$StudentCursor= $this->StudentCollection->find(array("student_id" => $studentId));
if($StudentCursor->count() > 0)
{
foreach ($StudentCursor as $k => $srow) {
array_push($result, $srow);
}
}
else
{
array_push($result, array("datanotfound"=>1));
}
}
}
return json_encode($result);
After fetching "studentList" from broadcastTbl table and $idstring has "5042|5043|5044" values which are student ids of studentTbl. Now I am trying to fetch corresponding students details by splitting them one by one on the basis of "|". After that I am trying to push them in array $result.
It always displays $StudentCursor->count() as "1" and never enter in else block even if find() query fails to find record and then it displays output as [] i.e it always stay in if statement !!!
Please help me in tracking out what is wrong in the code and writting it efficiently!!!

How to change a php array

Simple question to which I don't have an answer.
How can I change my array from this:
[{"sku":"6"},{"buyers":"7"},{"base":"8"}]
to this:
[{"sku":"6","buyers":"7","base":"8"}]
I have three queries for three different database tables:
$sku = DB::table('mapiranje')->select(DB::raw('count(*) as sku'))
->where('mate_fk', '=', NULL)
->get();
$kupac = DB::table('mapkupci')->select(DB::raw('count(*) as buyers'))
->where('kupci_fk', '=', NULL)
->get();
$base = DB::table('dist_base')->select(DB::raw('count(*) as base'))
->where('base_fk', '=', NULL)
->get();
now each returns:
[{"sku":"6"}]
[{"buyers":"6"}]
[{"base":"6"}]
I have used merge_array to make a single array, but I get:
[{"sku":"6"},{"buyers":"7"},{"base":"8"}]
what I want is:
[{"sku":"6","buyers":"7", "base":"8"}]
Refactor your code according to right Laravel way:
$result = [
'sku' => DB::table('mapiranje')->whereNull('mate_fk')->count(),
'buyers' => DB::table('mapkupci')->whereNull('kupci_fk')->count(),
'base' => DB::table('dist_base')->whereNull('base_fk')->count()
];
$result = [];
foreach($input as $oneInputRow) {
$result[$oneInputRow[0]] = $oneInputRow[1];
}
$target = array();
$start = array(array("sku"=>"6"), "buyers"=>"7"), "base"=>"8"));
foreach($start as $sub){
foreach($sub as $key => $val){
$target[$key] = $val;
}
}
Not shure if laravel provides any special syntax, but just with php I'd do it as above.
Basicly you loop over the start-array. In that you loop over every array to get the key/val combination and put that into the target-array.
For the second loop there would be other ways if you only have one entry in every secondary array.
Please try below code
$dd = '[{"sku":"6"},{"buyers":"7"},{"base":"8"}]';
$data = json_decode($dd,true);
$result = array();
foreach($data as $key=>$value){
foreach($value as $key1=>$value1){
$result[$key1] = $value1;
}
}
echo json_encode($result); //this will print your required format result

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

PHP: Timestamp sorting

I am making an image website and I need help with timestamp sorting. I have about 5 different SQL queries to get information from the database. Each one of these queries get the timestamp.
What I want to do is get it from the database, and sort the images from all of the queries with a foreach loop. This may sound confusing, just comment if you don't understand.
$images = array();
$stmt = $conn->prepare("SELECT images.*, group_images.* ORDER BY `timestamp` DESC");
$stmt->execute();
while ($images_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$images[] = array(
'image_id' => $images_row['image_id']);
}
return $images;
foreach($images as $image) {
echo $image['image_id'];
echo '<br/>';
}
That is a query I attempted to try which turned out not to work.
Error:
$images = valley_images();
$sorted_data = array();
foreach($images as $key => $value) {
if ($key == 'timestamp') {
$sorted_data[$value][] = $images;
}
}
ksort($sorted_data);
If I understand you correctly, this might help:
$data; //data from database, assuming it has a "timestamp"-key
$sorted_data = array();
foreach ($data as $key => $value) {
if ($key == 'timestamp') {
$sorted_data[$value][] = $data;
}
}
ksort($sorted_data);
With that you get an array that is ordered by the timestamps of your values from the database. If there is only one entry to each timestamp you can spare the [].

how to merge keys with same value?

code;
$all_tags = array();
while ($row = mysql_fetch_assoc($result)) {
$all_tags = array_merge($all_tags, explode(' ', $row['title']));
}
$all_tags = array_count_values($all_tags);
echo "<pre>";
arsort($all_tags);
foreach ($all_tags as $key => $val) {
echo "$key = $val\n";
}
output;
fuups! = 7
401 = 5
Authorization = 5
Required = 5
, = 3
izle = 3
Error = 2
Server = 2
Internal = 2
500 = 2
Full = 1
MegaSinema.net = 1
Sinema = 1
Bad = 1
Request = 1
Film = 1
400 = 1
all i wanna do is merge 'keys' with same integer 'value'. example;
401 = 5
Authorization = 5
Required = 5
to
401 Authorization Required = 5
i don't know how could i do it. i tried a bunch of ways but i never let it work. thank you.
I misunderstood you in the beginning.
I think you could just save the objects in an array and implode them if needed.
$out = array();
foreach($array as $key=>$value)
if(array_key_exists($value, $out))
$out[$value][] = $key;
else
$out[$value] = array($key);
// Then you could do
echo implode(" ", $out[5]); // Should output "401 Authorization Required"
Working example at http://codepad.org/MgLKXA75
Another option is to directly append it and trim the "extra" space at the end.
$out = array();
foreach($array as $key=>$value)
if(array_key_exists($value, $out))
$out[$value] .= $key . ' ';
else
$out[$value] = $key . ' ';
// Then you could do
echo trim($out[5]); // Should output "401 Authorization Required"
Try this
<?php
$data = array('fuups!' => '7','401' => '5','Authorization' => '5','Required' => '5',',' => '3','izle' => '3','Error' => '2','Server' => '2','Internal' => '2','500' => '2','Full' => '1','MegaSinema.net' => '1','Sinema' => '1','Bad' => '1','Request' => '1','Film' => '1','400' => '1');
$rows = array();
$values = array_values($data);
asort($values);
$highestVal = $values[0];
for ($i = 0; $i <= $highestVal; $i++) {
foreach ($data as $key => $value) {
if ($i == $value) {
$rows[$i] = $rows[$i] . " {$key}";
}
}
}
?>
Working Example XD http://codepad.org/x9uHs1sp
EDIT----
To echo all keys, just replace var_dump($rows) with:
foreach ($rows as $key) {
echo "{$key}<br />";
}
I'm not familiar with PHP, but I think you can try to create a hash table to handle this.
For example, if you insert above 3 items into the hash table and use '5' as the key, the first item can be inserted correctly, and the other two should throw exceptions. You can catch the exception since it's excepted and append the values to the value of the first item. So the item in you hash table should be like:
key: 5
value: 401 Authorization Required
But you should make sure about the orders in the value.
Just my 2 cents, good luck!
Update:
If throwing exception is not acceptable, you can look-up a key in the hash table first, if the key doesn't exist then insert the key and value, if it already exists then append the value to existing item value.

Categories