PHP and Pods: Combine array values only into new array - php

Long time user, first time poster. The forums here have got me out of a lot of trouble but I'm really stuck on this one.
I'm using Pods for a Custom Post Type that has a Custom Field where a user can enter a numeric value. eg. or 4 or 2 etc
I want to display the total sum of this Custom Field across all user made posts on the front end. To achieve this I'm using a Pods Template to make a short code for the front end, but to do the calculation I'm using PHP.
So my current PHP is:
function jobs_total ($id) {
$pods = pods ('pledged_job', $id);
$jobs = ($pods->field ('jobs_pledged'));
$a = ($jobs);
$b = explode(' ', $a);
var_dump($b);
}
And the result I get so far is:
array(1) { [0]=> string(1) "5" }
array(1) { [0]=> string(1) "4" }
array(1) { [0]=> string(1) "2" }
array(1) { [0]=> string(1) "7" }
How do I take the numeric values from "_", which are correctly appearing from post entries, and combine them in a new array so I can perform an 'array_sum' and return the total of those numbers?!
I'm a PHP novice so I'm not sure if this is obvious or if it's a clash between Pods terms and standard PHP.
Thanks in advance!!

Final code wrapped in shortcode to allow for displaying on the frontend through Elementor
function jobs_shortcode () {
$jobs = get_posts(array(
'post_type' => 'pledged_job',
'post_status' => 'publish',
'numberposts' => -1, ));
$total = 0;
foreach ($jobs as $field) {
$total += (int) get_post_meta($field->ID, 'jobs_pledged', true);
}
echo $total;
}
add_shortcode( 'jobs', 'jobs_shortcode' );

Related

take out components from array session and save in Database LARAVEL 9

How are you? Hope well. I have e-commerce project on laravel 9. Actually i want to make checkout. I have add to cart function with sessions(it works fine), i want to make checkout. I am recieving cart with sessions
$order = session('cart');
var_dump($order);
This is working fine. It makes output with array('title','price','quantity'). Actually i want to put out each other and next save it in database.
array(1) { [52]=> array(3) { ["title"]=> string(11) "MacBook Pro" ["quantity"]=> int(1)
["price"]=> string(7) "2399.99" } }
This is array, which i have in checkout page. Please help me. I want to put out each other, for example: $order_title = ....
$order_price = ...
$order_quantity = ...
and next save it in database, table named 'orders'.
Just insert / add the data how you do normally.
$carts = session('cart');
foreach($carts as $cart)
{
Order::create([
'order_title' => $cart['title'],
'order_quantity' => $cart['quantity'],
'order_price' => $cart['price'],
]);
}
first read data from session then iterate through elements of array and save them:
$carts = session('cart');
foreach($carts as $cart) {
$order = new Order();
$order->order_title = $cart['title'];
$order->order_quantity = $cart['quantity'];
$order->order_price = $cart['price'];
$order->save();
}

Why does my function work fine in some places of Elementor Pro but gives a TypeError in other places?

I'm creating a widget that's compatible with Elementor Pro but I'm getting a
Fatal Error: Uncaught TypeError: Elementor\Controls_Stack::sanitize_settings(): Argument #1 ($settings) must be of type array, null given.
I'm trying to create a select field and the array I'm returning are the options for the select field. I have other select fields that work just fine with a returned array but I can't figure out why this one doesn't work. I've done a var_dump of the variable to verify it is an array and to see the contents of the array. Everything looks fine.
I also did a test by manually creating a simple array to return and that worked. Here is my function:
/**
* Get a list of the custom field names from the selected post type
*/
protected function get_post_fields(){
/***** This code works fine but isn't what I need***************
$post_fields = [
'default' => esc_html__( 'Default', 'OWSM-table-widget' ),
'yes' => esc_html__( 'Yes', 'OWSM-table-widget' ),
'no' => esc_html__( 'No', 'OWSM-table-widget' ),
];
return $post_fields;
***************************************************************/
//Get the selected post type
$my_settings = $this->get_settings_for_display();
$selected_post_type = $my_settings['data_source'];
//Array to store field names
$field_names = array();
//Check to make sure there is a selected post type
if (!$selected_post_type) {
return;
}
//Get the selected post type, loop through and get custom post field names
$wanted_posts = new WP_Query(array('post_type' => $selected_post_type));
if($wanted_posts->have_posts()) :
while($wanted_posts->have_posts()) : $wanted_posts->the_post();
// Get all the custom data
$getPostCustom = get_post_custom();
//Store the names of the custom fields in an array
foreach($getPostCustom as $name=>$value) {
if (strpos($name, "_") !== 0){
$field_names[$name] = esc_html__($name, 'OWSM-table-widget');
}
}
endwhile;
endif;
// Return to the current page's main query
wp_reset_query();
//Return the array of custom fields for the specified post type
return $field_names;
}
Here's the var_dump of the manually created array $post_fields:
array(3) { ["default"]=> string(7) "Default" ["yes"]=> string(3) "Yes" ["no"]=> string(2) "No" }
And here's the var_dump of the $field_names array created with the loop:
array(5) { ["city"]=> string(4) "city" ["nights_of_play"]=> string(14) "nights_of_play" ["contact"]=> string(7) "contact" ["email"]=> string(5) "email" ["phone"]=> string(5) "phone" }
Both arrays have the exact same structure but the $field_names array gives me the error. Any suggestions?

CakePHP: Custom pagination with an array

I am trying to paginate an array in CakePHP. The array is extracted from a JSON file, thus not using any database queries or whatsoever. I'm trying to stick to the functions of CakePHP to make sure I don't write useless code. I have been looking around and can not find any answer on my question.
The array is as of the following:
array(161) {
[0]=> array(8) {
["id"]=> int(589)
["status"]=> string(7) "running"
["threads"]=> int(12)
["create_time"]=> float(1487712882.42)
["memory_usage_precent"]=> float(11.0328674316)
["cpu_usage_precent"]=> int(62)
["cwd"]=> string(1) "/"
["process_name"]=> string(16) "plugin-container"
}
}
This is one row of the 161 rows in the array. How can I paginate this by using CakePHP's methods?
Here is an example for making pagination from Array
Step 1 - PHP Data Array :
$data = [
[
"id"=> 0,
"status"=> "running"
],[
"id"=> 1,
"status"=> "running"
],
#More Arrays ...
];
Step 2 - Prepare Data [Calculations]
$TotalDatas = count($data); #Total number of Data in Array
$StartFrom = 0; #Start from Array index
$DisplayLimit = 2; #Limit the result per page
$CurrentPage = isset($_GET['page'])? $_GET['page'] : 0; #Get the page number value from URL
$StartFrom = $CurrentPage*$DisplayLimit; #Update the Array index by calculating Page number and Limit
Step 3 - Display Data using loop :
for($i=$StartFrom; $i<$StartFrom+$DisplayLimit; $i++){ #Increase the Array index by Limit
if($i>=$TotalDatas){
continue; #Break Or put some message, Because no more Data in Array
}
var_dump($data[$i]);
}
Browse URL like as - localhost?page={PAGE_MUNBER_HERE}
Example :
localhost?page=3
Note : Above codes is the simple example of basic pagination.

return passed array keys and values

I am working in WordPress. I am using a plugin to get the admin options. The plugin takes an argument as an ID to get the value from the database like so.
$option = ot_get_option('email_address');
The above line of code would return
myEmail#example.com
I want to write a helper function that would get multiple values at once. Normally, I would get the options like this.
$option_1 = ot_get_option('option1');
$option_2 = ot_get_option('option2');
$option_3 = ot_get_option('option3');
I figured there could be a better way that would look a little nicer. I put together this little function that does work
function ritual_get_options($arg_list = array())
{
$options = array();
foreach( $arg_list as $key => $value){
$options[] = ot_get_option($value, array());
}
return $options;
}
using the function above, I can now pass the id's of the options like so
ritual_get_options('option1','option2','option3');
My issue is that the above will return an array with numeric keys. 0,1,2. Here is the exact array that is getting returned when I do a var_dump on the front end
[0]=>
string(16) "100 Main Street,"
[1]=>
string(18) "Hamilton, Ontario."
[2]=>
string(15) "+1 800 999 9898"
[3]=>
string(19) "mail#yourdomain.com"
I want to return the array keys with the value so that I can easily figure out what value is in what key. Here is the line that I used to get the above array
$options = ritual_get_options(array('number' => 'streetnumber','street' => 'street','phone' => 'phone_number','email' => 'email'));
When I go to use the returned values, I want to be able to use the key so that I could do
echo $options['number'];
instead of doing
echo $options[0];
I have not been able to figure out how to return the keys passed in to the function and preserve them into through the return.
Set the option name as key while building the array:
foreach( $arg_list as $option ){
$options[$option] = ot_get_option( $option );
}
Btw, using extract() on the $options array will allow you to use e.g. $phone_number instead of $options['phone_number']

Understanding CodeIgniter objects and multidimensional arrays

I'm working on a project in CodeIgniter 2 and now I'm stuck on the most basic of concepts.
Model:
Get an object array from my table which contains all rows that match a specific value for a field named foo. There can be one or more rows that match. In this example, two rows.
public function get_sample($foo)
{
$query = $this->db->get_where('sample_db', array('foo' => $foo));
return $query->result();
}
Controller:
Assign the results and make output available to view.
public function view($foo)
{
$data['array'] = $this->sample_model->get_sample($foo);
$this->load->view('view', $data);
}
View:
echo var_dump($array); // for testing
echo $array[1]->text
var_dump() of $array:
array(2) {
[0]=> object(stdClass)#23 (4) {
["id"]=> string(1) "1"
["foo"]=> string(3) "bar"
["number"]=> string(4) "1234"
["text"]=> string(23) "This is content in 1234"
}
[1]=> object(stdClass)#24 (4) {
["id"]=> string(1) "2"
["foo"]=> string(3) "bar"
["number"]=> string(4) "9999"
["text"]=> string(23) "This is content in 9999"
}
}
The rendered ouput of echo $array[1]->text; is: This is content in 9999
And I understand how all that is working: $array[1]->text is the content of the text field in the array object with the index of 1, my second object.
However, I have a field called number and I want to access the object with a certain number and get its corresponding text value.
Example: How can I retrieve the value of text where the number is 9999? I cannot use $array[1]->text since I can never be sure of the object's position in the array. Something like $array['number' => '9999']->text, but I know that's not right. Maybe I need to loop through the array looking for a match?
This looks so simple yet everything I've tried has failed and resulted in various PHP errors. I've been studying the PHP manual here and here, but cannot seem to find anything about what I'm looking to do, or maybe I'm just misapplying what I'm reading. Any guidance is appreciated.
In addition to an answer using best practices following the MVC model, I'm hoping for a link to the proper page in the documentation, as well as pointing out any errors in my wording/terminology above.
EDIT:
This answer contains the actual code I used to solve my problem. Although, Yagi's answer was accepted because it put me in the right direction.
How about using this :
foreach ($array as $row) {
if ($row->number == '9999') {
echo $row->text;
}
}
Loop through the array, and find the number object value of 9999 and get the text
Why don't you just to a query and search for that number (or order by that number?)
Either way, what you need is a multidimensional array search function (that iterates through array of object and returns the found field value combo )
Something like this (put this in helper)
function multi_array_search($array, $field, $value)
{
$results = array();
if (is_array($array))
{
if ($array->$field == $value) //chek the filed against teh value, you can do addional check s(i.e. if field has been set)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, multi_array_search($subarray, $key, $value)); //recurisve serach
}
return $results;
}
//than in view or in controller, depending where you need it
$result = multi_array_search($array, "number", "9999");
var_dump($result) will return or whether number of foudn instances
array() {
[0]=> object(stdClass)#24 (4) {
["id"]=> string(1) "2"
["foo"]=> string(3) "bar"
["number"]=> string(4) "9999"
["text"]=> string(23) "This is content in 9999"
}
}
you might be looking for something like this...
array_filter($array, function($o){ return $o->number == 9999; } );
http://php.net/manual/en/function.array-filter.php
EDIT
$o is the parameter in the callback function. each element of the array is passed to the callback function. if the function returns false, the element will be filtered out.
$arr = array(
(object) array(
'num' => 33,
'text' => 'hello',
),
(object) array(
'num' => 44,
'text' => 'world',
),
);
$filtered = array_filter($arr, function($o){ return $o->num == 33; });
echo $filtered[0]->text; // hello
as you stated, index will remain, so use array_values or array_shift. here's an example with function
function get_by_num($arr, $num){
return array_shift(array_filter($arr, function($o) use ($num) { return $o->num == $num; }));
}
$obj = get_by_num($arr, 44);
var_dump($obj);
// object(stdClass)#2 (2) { ["num"]=> int(44) ["text"]=> string(5) "world" }
in this case $obj will be either NULL if element is not found, or the first match. $num is transferred along so you can use any value. you can even improve it:
function get_first_match($arr, $field, $val){
return array_shift(array_filter($arr, function($o) use ($field, $val) { return $o->{$field} == $val; }));
}
$obj = get_first_match($arr, 'num', 44);
and now you can search any field. in your case
$obj = get_first_match($array, 'number', 9999);
Thanks to Yagi's answer, I came up with the following very simple solution. I loop through the array and assign the value of text to a new array with an index that matches the value of number. Then in the view file, I can access the text value based on this index.
Controller:
public function view($foo)
{
$data['array'] = $this->sample_model->get_sample($foo);
foreach ($data['array'] as $row) {
$data['result'][$row->number] = $row->text;
};
$this->load->view('view', $data);
}
View:
if (isset($result[9999])) echo $result[9999];

Categories