How do i grab all users with their meta data? - php

I am building out a website that has about 7500 users. What i wanted was to grab all of my users and their meta data and return it to me through a rest api call that I built myself. Currently I am having a hard time returning all of our users meta data and not just one single user's meta data.
I have already built out the custom endpoint and can successfully return users
add_action( 'rest_api_init', 'my_register_route' );
function my_register_route() {
register_rest_route( 'map/v1', 'test', array(
'methods' => 'GET',
'callback' => 'custom_phrase',
)
);
}
function custom_phrase() {
$users = get_users( array( 'fields' => array( 'ID' ) ) );
foreach($users as $user_id){
return (get_user_meta ( $user_id->ID));
}
}
I expect that the endpoint will return all of my users meta_data & user_data together instead of just the final user in the index.
UPDATE: I feel like I am almost there but each index in the array comes back with the exact same information. Not to mention i am somehow unsuccessful at grabbing the Active_Memberships values which is an array before it gets to me.
function custom_phrase($request_data) {
$parameters = $request_data->get_params();
$state = $parameters['state'];
$users = get_users(array(
'meta_key' => 'active state membership',
'meta_value' => $state,
));
$stack = array();
foreach($users as $user_id) {
$user_meta = get_user_meta ($user_id -> ID);
$obj->display_name = $user_id -> display_name;
$obj->memberships = $user_meta -> active_memberships;
array_push($stack, $obj);
}
return $stack;
}

You use return in your loop, so it will return at the first iteration.
Just create a variable to store meta :
function custom_phrase() {
$users = get_users( array( 'fields' => array( 'ID' ) ) );
$data = [];
foreach($users as $user_id){
$data []= get_user_meta ( $user_id->ID);
}
return $data;
}

Related

How to create 2 collections based from an array with 2 count in PHP?

I know this is a basic question and I'm sorry I can't answer, but how can I create 2 collections based from an array with 2 values in Laravel/PHP? Here's my code:
$received_items = ReceiveItems::where('voucher_id', '=', $request->voucher_id)->get();
foreach($received_items as $received_item) {
$product_ids = $received_item->product_id;
foreach($product_ids as $product_item_no => $product_id) {
$products = Product::where('id', '=', $product_id);
$voucher_cost = $products->value('cost');
$qty_addend = $received_item->qty_per_item;
$list = array(
'product_item_no' => $product_item_no + 1,
'product_name' => $products->value('name'),
'size' => $products->value('size'),
'qty_addend' => $qty_addend[$product_item_no],
'voucher_cost' => $voucher_cost,
'ext_cost' => number_format($voucher_cost * $qty_addend[$product_item_no], 2)
);
$list = (object)$list;
$received_item->list = $list;
$data = collect([$list]);
}
}
return $data;
Basically, the $product_ids is the array I want to get and count($product_ids) is returning 2, but it's just creating the collection from the 2nd array value. See screenshot below:
screenshot.png
Any help is much appreciated.
In your $list variable it will only store last product_id data, because you have to take $list as multi-dimensional array.
You have to take $list variable out of the second loop, so it not overwrite data.
Try below code:
$received_items = ReceiveItems::where('voucher_id', '=', $request->voucher_id)->get();
foreach($received_items as $received_item) {
$product_ids = $received_item->product_id;
$list = []; // declare list variable here
foreach($product_ids as $product_item_no => $product_id) {
$products = Product::where('id', '=', $product_id);
$voucher_cost = $products->value('cost');
$qty_addend = $received_item->qty_per_item;
$list[] = array( // make it multi-dimentional array
'product_item_no' => $product_item_no + 1,
'product_name' => $products->value('name'),
'size' => $products->value('size'),
'qty_addend' => $qty_addend[$product_item_no],
'voucher_cost' => $voucher_cost,
'ext_cost' => number_format($voucher_cost * $qty_addend[$product_item_no], 2)
);
}
// take this code out of loop
$list = (object)$list;
$received_item->list = $list;
$data = collect([$list]);
}
return $data;

How to return all objects where a string is matching?

i'am searching a way to solve this problem , I just modified the return of the rest API search endpoint in Wordpress, in order to get a specific format of object.
public function custom_api_search_posts_callback(WP_REST_REQUEST $request)
{
// Initialize the array that will receive the posts' data.
$posts_data = [];
// Receive and set the page parameter from the $request for pagination purposes
$paged = $request->get_param('page');
$paged = (isset($paged) || !(empty($paged))) ? $paged : 1;
$posts = get_posts([
'paged' => $paged,
'post__not_in' => get_option('sticky_posts'),
'posts_per_page' => 300,
'post_type' => ['pizzas', 'tagliate', 'les_antipasti', 'la_carne', 'ptes_et_risottos', 'les_desserts', 'les_boissons', 'vins', 'les_cocktails', 'cichetteria'] // This is the line that allows to fetch multiple post types.
]);
// Loop through the posts and push the desired data to the array we've initialized earlier in the form of an object
foreach ($posts as $post) {
$id = $post->ID;
$meta = get_post_meta($id);
$search = 'calz';
$posts_data[] = (object)[
'id' => $id,
'type' => get_post_type_object($post->post_type)->labels->name,
'slug' => $post->post_type,
'content' => ['rendered' => $post->post_content],
'title' => ['rendered' => $post->post_title],
'categories' => $this->transformCategory($id),
'meta' => $this->transformMeta($id),
];
}
//here i would like to get all the object matching the search
enter code here
foreach ($posts_data as $key => $element) {
if (stristr($element->title['rendered'], $search) !== false) {
return $posts_data[$key];
//with stristr it returns only the first result
}
}
}
This is because you're returning after the first 'match'. You should build a results array that collects all matches and when the foreach has finished going through all the posts, return the results $results:
...
foreach ($posts_data as $key => $element) {
if (stristr($element->title['rendered'], $search) !== false) {
// return $posts_data[$key];
$results[] = $posts_data[$key];
//with stristr it returns only the first result
}
}
return $results;
}

How to fix "Call to a member function execute() on string" on my function

I'm modifying a Wordpress API witch is currently getting learnpress course and lessons infos from the database using leanrpress functions only. I need to modify the API to get the scores from the newly implemented plugin h5p, therefor i need to make a new function to access the Database and get the scores from the right table, then put then into an array with the according lesson. The array here is only an exemple i'm using to see if i can get the datas, ut i'm stuck with the error
"Call to a member function execute() on string"
when i try and run it on postman. Could someone lighten me on this issue please ?
function ilp_api_get_progress_by_mail($data){
$mail=$_GET['mail']; //$data->get_param["mail"];
$course_id=$_GET['course'];
global $wpdb;
$user=get_user_by("email",$mail);
if($user !== false){
$lp_user=learn_press_get_user( $user->ID );
if($course_id==NULL){
$all_courses=ilp_api_get_all_courses($data);
}else{
$all_courses=array('courses' => array(array('id' => intval($course_id))));
}
$progress=array();
$i=0;
if($all_courses!=NULL && $all_courses['courses']!=null){
foreach($all_courses['courses'] as $course){
if($lp_user->has_enrolled_course($course['id'])){
$lp_course=learn_press_get_course( $course['id'] );
$course_data = $lp_user->get_course_data($course['id']);
$course_results = $course_data->get_results( false );
$progress[$i]=array(
'id' => $course['id'],
'name' => $lp_course->get_title(), //$course['name'],
'condition' => $lp_course->get_passing_condition(),
'completed' => $course_results['completed_items'],
'total' => $course_results['count_items'],
'progress' => absint( $course_results['completed_items'] / $course_results['count_items'] * 100 ),
'permalink' => $lp_course->get_permalink(),
);
$i++;
}
}
}
$result = array(
'userfound' => true,
'user_id' => $user->ID,
'connect' => get_h5p_grades(),
'courses_progress' => $progress,
'course_id' => $all_courses,
);
function get_h5p_grades(){
global $wpdb;
$ID = 1;
$ID_use = 1;
$result = $wpdb->prepare('SELECT score FROM mci_h5p_results WHERE id = %d AND user_id = %d', $ID, $ID_use);
$result->execute();
$donnees = $result->fetch();
return $donnees;
}

sql updating whole data in database

I have written code to add and update users and also I want to add and update categories they can work in. The added users will go in users table and the categories they can access goes in the category_permitted table. I have the following code for adding and updating tables:
if ($user_info) {
if ($act == "add") {
if ($user_info) {
$array = array(
'user_id' => $user_info,
'category_id' => $temp['cat_access']
);
$category_permitted->addCategoryAccess($array);
}
} else {
if ($user_info) {
$array = array(
'user_id' => $id,
'category_id' => $temp['cat_access']
);
$deleteold = $category_permitted->deleteCategoryAccess($id);
$category_permitted->addCategoryAccess($array);
}
}
}
This my function to add and update category access:
public function addCategoryAccess($data, $is_die = false){
return $this->insert($data, $is_die);
}
public function updateCategoryAccess($data, $id, $is_die = false){
$args = array(
'where' => array('user_id' => $id),
);
return $this->update($data, $args, $is_die);
}
And this is the data in database table .
My update function is updating all data of the column category_id with the number being added while updating category access for the user.
I want to leave 2 and 3 as it is and add another category id which is 1 but after running the update code it updates the data like this. Do I have to add another condition to WHERE CLAUSE to get the expected output?
To update only one row you need an unique identifier for that row.
If the column id is the primary key, you can use that column to update only the corresponding row.
$args = array(
'where' => array('id' => $category_permitted_id),
);
As an alternative, if you know which category is changing, and the relation (user_id,category_id) is unique, you can add the changing category to the where.
$args = array(
'where' => array(
'user_id' => $user_id,
'category_id' => $category_id
),
);
Please note that i don't know your Database abstraction layer and i'm implying that you can simply add another entry in the array to put conditions in 'AND', this could be wrong in your case.
Managing relationships this way takes a bit of effort, and in my opinion is not worth it.
If you are able to modify the application logic, i suggest you to switch to using only insert/delete, like so:
Add a permitted category: Just add it creating a new record with insert
Remove a permitted category: Remove it trough a delete function
Change a permitted category to another: Delete the one that is changing and add the new one
Doing this in my code worked for me. I called the function $deleteold = $category_permitted->deleteCategoryAccess($id); just before the for loop to avoid deleting the previous data being deleted in every iteration.
if ($user_info) {
$cat_access = (isset($_POST['cat_access']) && !empty($_POST['cat_access'])) ? ($_POST['cat_access']) : $_SESSION['cat_access'];
$value = array();
if (!empty( $cat_access ) && is_array( $cat_access ) ) {
foreach( $cat_access as $key => $item ) {
$value[] = filter_var( $item, FILTER_SANITIZE_NUMBER_INT );
}
}
$categoryData = $value;
$temp = array();
if ($categoryData) {
$count = count($categoryData);
if ($count > 0) {
$deleteold = $category_permitted->deleteCategoryAccess($id);
for($i=0; $i<$count; $i++){
$temp =array(
'cat_access' => $categoryData[$i]
);
if ($act == "add") {
if ($user_info) {
$array = array(
'user_id' => $user_info,
'category_id' => $temp['cat_access']
);
$category_permitted->addCategoryAccess($array);
}
} else {
if ($user_info) {
$array = array(
'user_id' => $id,
'category_id' => $temp['cat_access']
);
$category_permitted->addCategoryAccess($array);
}
}
}
}
}
}

Selecting from database in controller with laravel

I'm trying something really simple and yet doesn't work. I have one controller where selecting from one database to show some info for user. Now I'm trying in this same controller to select from second table to show some other info but I get Undefined variable...
This is the part of controller which is problematic
public function orderView( $orderId, $userId ) {
$order = self::$user->orders()->where('order_id', $orderId)->first();
$keys = Keys::all();
if (!$order) {
App::abort(404);
}
$userID = $order['user_id'];
$orderID = $order['order_id'];
$public_key = $keys['public_key'];
$private_key = $keys['private_key'];
$options = array(
"public_key" => $public_key,
"private_key" => $private_key,
"orderID" => $orderID,
"userID" => $userID
);
What I have added here is
$keys = Keys::all();
$public_key = $keys['public_key'];
$private_key = $keys['private_key'];
....
"public_key" => $public_key,
"private_key" => $private_key,
The error is Undefined index: public_key
Keys::all() returns an Illuminate\Database\Eloquent\Collection.
In order to access a single item of the Collection, you either must iterate the collection and access them singularly, or take one item specifically with Collection's functions, such as first().
For example:
public function orderView($orderId, $userId)
{
$order = self::$user->orders()->where('order_id', $orderId)->first();
$keys = Keys::all();
if (! $order) {
App::abort(404);
}
$options = [];
foreach ($keys as $key)
{
$options[] = [
'public_key' => $key->public_key,
'private_key' => $key->private_key,
'userID' => $order->user_id,
'orderID' => $order->order_id
];
}
return $options;
}
You can find more information about Illuminate Collection methods here.

Categories