I want to make multidimensional array by fetching data from the database. The second array which is podcast added by a specific user is created however, it is not giving the output of another user which is active in the database.
Here is my code:
require $_SERVER['DOCUMENT_ROOT'].'/config/init.php';
require CLASS_PATH.'user.php';
require CLASS_PATH.'podcast.php';
$user = new User();
$podcast = new Podcast();
$userList = $user->getAllUserName();
foreach ($userList as $users) {
$fullname = $users->first_name. ' '. $users->last_name;
$data = array(
'name' => $fullname
);
$podcastList = $podcast->getUserPodcast($fullname);
$data['podcast'] = $podcastList;
}
You need to build a list of the data up. Creating the data as 1 item will stop the podcast data being separated from the fullname...
$userList = $user->getAllUserName();
$data = [];
foreach ($userList as $users) {
$fullname = $users->first_name. ' '. $users->last_name;
$data[] = array(
'name' => $fullname,
'podcast' => $podcast->getUserPodcast($fullname)
);
}
To only users with podcasts...
$userList = $user->getAllUserName();
$data = [];
foreach ($userList as $users) {
$fullname = $users->first_name. ' '. $users->last_name;
$podcast = $podcast->getUserPodcast($fullname);
if ( !empty($podcast) ) {
$data[] = array(
'name' => $fullname,
'podcast' => $podcast
);
}
}
Related
I need merge arrays for json API. I have 3 requests:
$data['winners'] = Winners::find()->limit(8)->all();
$user = User::findIdentity($value->user_id);
$product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
I need foreach all $data['winners'], get User with id from $data['winners'], and get Product from $data['winners']. After i need merge in 1 json all my data.
I try like this:
$data['winners'] = Winners::find()->limit(8)->all();
foreach ($data['winners'] as $value){
$user = User::findIdentity($value->user_id);
$product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
$result = ArrayHelper::merge($product, $user);
}
There is an even more elegant solution in PHP:
$winners = Winners::find()->limit(8)->all();
foreach ($winners as $value){
$user = User::findIdentity($value->user_id);
$product = Products::find()->localized($lang)
->where(['coupon' => $value->coupon])->one();
$data[] = [
'image'=> $product->prize_image,
'user' => $user->firstname.' '.$user->lastname,
'title' => $product->win_title,
];
}
return $data;
The PHP array operator [] in $data[] adds an array element at the end of the $data array.
If i understand correctly you question you need an array with all the $data[winners] istances and foreach instance merge the related Produce and User
then you could use
$result[] = array_merge($value, $product, $user);
.
$data['winners'] = Winners::find()->limit(8)->all();
foreach ($data['winners'] as $value){
$user = User::findIdentity($value->user_id);
$product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
$result[] = array_merge($value, $product, $user);
}
I found solution:
$winners = Winners::find()->limit(8)->all();
$i = 0;
foreach ($winners as $value){
$user = User::findIdentity($value->user_id);
$product = Products::find()->localized($lang)->where(['coupon' => $value->coupon])->one();
$data[$i]['image'] = $product->prize_image;
$data[$i]['user'] = $user->firstname.' '.$user->lastname;
$data[$i]['title'] = $product->win_title;
$i++;
}
return $data;
I am trying to insert/update +/- 10k rows with a foreach loop. The complete loop duration is about 3-5minutes. Are there any tips on my code to do the insertion of update faster? The $rows are retrieved from a xls file converted to domdocument.
foreach($rows as $key => $row)
{
if($key < 1){continue;}
$cells = $row -> getElementsByTagName('td');
foreach ($cells as $cell) {
$project_id = $cells[0]->nodeValue;
$title = $cells[1]->nodeValue;
$status = $cells[2]->nodeValue;
$projectmanager = $cells[3]->nodeValue;
$engineer = $cells[4]->nodeValue;
$coordinator = $cells[5]->nodeValue;
$contractor_a = $cells[6]->nodeValue;
$contractor_b = $cells[7]->nodeValue;
$gsu = $cells[9]->nodeValue;
$geu = $cells[10]->nodeValue;
$query = $this->Projects->find('all')->select(['project_id'])->where(['project_id' => $project_id]);
if ($query->isEmpty()) {
$project = $this->Projects->newEntity();
$project->title = $title;
$project->project_id = $project_id;
$project->status = $status;
$project->projectmanager = $projectmanager;
$project->engineer = $engineer;
$project->coordinator = $coordinator;
$project->contractor_a = $contractor_b;
$project->contractor_b = $contractor_a;
$project->gsu = date("Y-m-d H:i:s");
$project->geu = date("Y-m-d H:i:s");
$project->gsm = date("Y-m-d H:i:s");
$project->gem = date("Y-m-d H:i:s");
if ($this->Projects->save($project)) {
//$this->Flash->success(__('The project has been saved.'));
continue;
}else{
debug($project->errors());
}
}else{
continue;
$query->title = $title;
$query->status = $status;
$query->projectmanager = $projectmanager;
$query->engineer = $engineer;
$query->coordinator = $coordinator;
$query->contractor_a = $contractor_b;
$query->contractor_b = $contractor_a;
$query->gsu = $gsu;
$query->geu = $geu;
if ($this->Projects->save($query)) {
//$this->Flash->success(__('The project has been saved.'));
continue;
}
}
}
//$this->Flash->error(__('The project could not be saved. Please, try again.'));
}
For faster bulk inserts don't use entities but rather generate insert queries directly.
https://book.cakephp.org/3.0/en/orm/query-builder.html#inserting-data
Ello, my vriend.
The TableClass->save() method is useful when saving one single record, in your case, you should use TableClass->saveMany() instead.
For this to happen, you need to treat your entities as arrays inside your foreach.
After the foreach, you will use another method from the tableclass (newEntities) to convert the array into entities before finally save them.
Basic example:
//Lets supose our array after our foreach become something like this:
$all_records =
[
//Each item will be an array, not entities yet
[
'name' => 'I.N.R.I.',
'year' => '1987',
'label' => 'Cogumelo',
'country' => 'Brazil',
'band' => 'Sarcófago',
'line_up' => '[{"name":"Wagner Antichrist","role":"Vomits, Insults"},{"name":"Gerald Incubus","role":"Damned Bass"},{"name":"Z\u00e9der Butcher","role":"Rotten Guitars"},{"name":"D.D. Crazy","role":"Drums Trasher"}]'
],
//Another record coming in..
[
'name' => 'Eternal Devastation',
'year' => '1986',
'label' => 'Steamhammer',
'country' => 'Germany',
'band' => 'Destruction',
'line_up' => '[{"name":"Marcel Schmier","role":"Vocals, Bass"},{"name":"Mike Sifringer","role":"Guitars"},{"name":"Tommy Sandmann","role":"Drums"}]'
]
];
//Time to get the tableclass...
$albums = TableRegistry::get('Albums');
//Time to transform our array into Album Entities
$entities = $albums->newEntities($all_records);
//Now, we have transformed our array into entities on $entities, this is the variable we need to save
if(!$albums->saveMany($entities))
{
echo "FellsBadMan";
}
else
{
echo "FellsGoodMan";
}
You can read more about here
function practise()
{
$this->load->database();
$qry = mysql_query("select * from demmo");
if (mysql_num_rows($qry) > 0)
{
while ($row = mysql_fetch_array($qry))
{
$created = $row['created'];
//from here
$qry = mysql_query("select * from demmo where created = '$created'");
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
$users[] = array('user_id' => $user_id, 'name' => $name);
}
$dotts[] = array('created' => $created2);
//till here
}
return array ($dotts,$users);
}
}
in demmo table i am trying to fetch data and showing that data according to date .the problem is that the code is only selecting one date from the table from created rows and showing that data only .fortunately data shown is not only last but the data with actual date.
You need to create an array and use array_push to get more than one result. Right now your code is only returning the last result of the while loop:
For example, to get all of the dates:
$dotts = array();
$allusers = array();
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
array_push($dotts, $created2);
$users[] = array('user_id' => $user_id, 'name' => $name);
array_push($allusers, $users);
}
//
return array ($dotts,$allusers);
You need to create an array and use array_push function , then only it will have more than one value.
example:
create an empty array as
$allUser = array();
then after this line
$users[] = array('user_id' => $user_id, 'name' => $name);
use array_push as
array_push($allUser, $users);
}
return array($dots, $allUser);
I ma using codeigniter to generate some html options,but i only get one result,first result from the table.
This is my controller
public function edit_event($id = 0){
$id = $this->uri->segment(3);
$current_id = $this->ion_auth->get_user_id();
$data['data'] = $this->as->the_event_edit($id);
$data['groups'] = $this->as->the_groups_list($current_id);
$this->load->view('editevent',$data);
}
This is my model
public function the_groups_list($current_id){
$query = $this->db->get_where('all_groups', array('group_owner' => $current_id));
foreach ($query->result() as $row)
{
$data = array(
'group_title' => $row->group_title,
'group_name' => $row->group_name,
'group_owner' => $row->group_owner
);
return $data;
}
}
This is the other model
public function as_event_edit($id){
$query = $this->db->get_where('all_scheduled_messages', array('id' => $id));
foreach ($query->result() as $row)
{
$data = array(
'as_title' => $row->as_title,
'as_event_name' => $row->as_event_name,
'as_owner' => $row->as_owner,
'as_type' => $row->as_type,
'as_target_dataset' => $row->as_target_dataset,
'as_timestamp' => $row->as_timestamp,
'as_time' => $row->as_time,
'as_day' => $row->as_day
);
return $data;
}
}
I am then using $groups['group_title'] in view and only the first group title gets displayed even though i have like 4 group titles from the other rows.
How can i return and pass an array that i can then to the view so as to use foreach to iterate and display the group titles?.
In your model you're not creating a multi-dimensional array. You need to add keys either using a counter:
$data = array();
$i=0;
foreach ($query->result() as $row){
$data[$i]['as_title'] = $row->as_title;
$data[$i]['as_event_name'] = $row->as_event_name;
$data[$i]['as_owner'] = $row->as_owner;
$data[$i]['as_type'] = $row->as_type;
$data[$i]['as_target_dataset'] = $row->as_target_dataset;
$data[$i]['as_timestamp'] = $row->as_timestamp;
$data[$i]['as_time'] = $row->as_time;
$data[$i]['as_day'] = $row->as_day;
$i++;
);
return $data;
or use the key of the incoming array
$data = array();
foreach ($query->result() as $id => $row){
$data[$id]['as_title'] = $row->as_title;
$data[$id]['as_event_name'] = $row->as_event_name;
$data[$id]['as_owner'] = $row->as_owner;
$data[$id]['as_type'] = $row->as_type;
$data[$id]['as_target_dataset'] = $row->as_target_dataset;
$data[$id]['as_timestamp'] = $row->as_timestamp;
$data[$id]['as_time'] = $row->as_time;
$data[$id]['as_day'] = $row->as_day;
);
return $data;
Change the model from $data = to $data[] = to insert each row and not only one.
In your view loop over the groups, like so:
foreach ($data as $group) {
echo "Title" . $groups['group_title'];
}
RTM: Adding Dynamic Data to the View
In the controller: rename your $data['data'] to $data['event']
$data['event'] = $this->as->the_event_edit($id);
$data['groups'] = $this->as->the_groups_list($current_id);
$this->load->view('editevent',$data);
In your view:
foreach ($event as $items) {
var_dump($items);
}
foreach ($groups as $group) {
var_dump($group);
}
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;
}
}
}