Use Array data in another function - php

I am hoping I can get some assistance with some issues I'm trying to get the array data from one function to be used in another function.
So in the function that's creating the array data, it looks like this:
function wlp_generate_pdf_and_save( $data, $post_id ){
// Function needing array data
}
function wlp_generate_preview($data, $generateType){
$out_product_brands = array();
if( count($all_posts) > 0 ){
foreach( $all_posts as $s_post )
{
...
$out_product_brands[] = array( 'brand' => vooHelperNew::get_posts_products( $s_post->ID ) );
...
}
}
}
This function "wlp_generate_preview" works perfectly, but it's this $out_product_brands data i need to use in the function (wlp_generate_pdf_and_save) above this one.
Does the order the functions are place change anything?

Return the data from wlp_generate_preview then pass it as a parameter of wlp_generate_pdf_and_save

First you want to return the array from your first function and then send that as a variable to the second function:
<?php
function wlp_generate_pdf_and_save( $data, $post_id, $input_array ){ //added a third
varible to this functions input
// Function needing array data
}
function wlp_generate_preview($data, $generateType){
$out_product_brands = array();
if( count($all_posts) > 0 ){
foreach( $all_posts as $s_post )
{
...
$out_product_brands[] = array( 'brand' => vooHelperNew::get_posts_products( $s_post->ID ) );
...
}
}
return $out_product_brands;//Returned The array
}
And then when calling your functions you might do something like this:
$input_array = wlp_generate_preview($data, $generateType);//Calls the first function
wlp_generate_pdf_and_save($data, $post_id, $input_array);//The third variable passes it into the next function

Related

Push Elements into an array inside a class in wordpress

i am trying to make a plugin through Worpress, i have in the frontend a list of generated plugins
like so Plugins
what i am trying to do is to get these plugins to be stored into an array inside the class and be printed or processed inside any function or a callback if i clicked submit. and here is the code.
class Example {
private static $init_core_plugins = array();
private static function handle_post() {
$save_settings = filter_input( INPUT_POST, 'save_settings' );
if ( !is_null( $save_settings ) && check_admin_referer( 'save-settings' ) ) {
self::save_settings();
self::refresh_page();
}
}
private static function save_settings() {
$core_plugins = filter_input( INPUT_POST, 'coreplugins', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
if ( empty( $core_plugins ) ) {
$core_plugins = [];
}
self::$init_core_plugins = array_merge( $core_plugins, self::$init_core_plugins );
// it shows here that it holds the correct selected plugins
echo "<pre>";
var_dump (self::$init_core_plugins);
echo "</pre>";
update_option( 'core_plugins_settings', $core_plugins );
}
public static function admin_render_main_page(){
// it shows here that it is an empty array
echo "<pre>";
var_dump (self::$init_core_plugins);
echo "</pre>";
}
}
What i am facing is somehow simple problem but i can't figure out where is the problem, when i called the array inside var_dump() inside save_settings() it printed the selected plugins from the list normally, but the problem is when later i try to var_dump (self::$init_core_plugins) in any other function like in the admin_render_main_page(), it returns as empty array, and the passed data through the save_settings() doesn't seem to be stored in the array.

PHP - Passing functions with arguments as arguments

I have several interchangeable functions with different numbers of arguments, for example:
function doSomething1($arg1) {
…
}
function doSomething2($arg1, $arg2) {
…
}
I would like to pass a certain number of these functions, complete with arguments, to another handling function, such as:
function doTwoThings($thing1, $thing2) {
$thing1();
$thing2();
}
Obviously this syntax is not correct but I think it gets my point across. The handling function would be called something like this:
doTwoThings(‘doSomething1(‘abc’)’, ‘doSomething2(‘abc’, ‘123’));
So the question is, how is this actually done?
From my research it sounds like I may be able to "wrap" the "doSomething" function calls in an anonymous function, complete with arguments and pass those "wrapped" functions to the "doTwoThings" function, and since the anonymous function doesn't technically have arguments they could be called in the fashion shown above in the second code snippet. The PHP documentation has me confused and none of the examples I'm finding put everything together. Any help would be greatly appreciated!
you could make use of call_user_func_array() which takes a callback (eg a function or class method to run) and the arguments as an array.
http://php.net/manual/en/function.call-user-func-array.php
The func_get_args() means you can feed this funciton and arbitary number of arguments.
http://php.net/manual/en/function.func-get-args.php
domanythings(
array( 'thingonename', array('thing','one','arguments') ),
array( 'thingtwoname', array('thing','two','arguments') )
);
funciton domanythings()
{
$results = array();
foreach( func_get_args() as $thing )
{
// $thing[0] = 'thingonename';
// $thing[1] = array('thing','one','arguments')
if( is_array( $thing ) === true and isset( $thing[0] ) and is_callable( $thing[0] ) )
{
if( isset( $thing[1] ) and is_array( $thing[1] ) )
{
$results[] = call_user_func_array( $thing[0], $thing[1] );
}
else
{
$results[] = call_user_func( $thing[0] );
}
}
else
{
throw new Exception( 'Invalid thing' );
}
}
return $results;
}
This would be the same as doing
thingonename('thing','one','arguments');
thingtwoname('thing','two','arguments');

foreach function not work on CodeIgniter

I have problems in function foreach, the resulting data is not showing all
data form database like below table names is "view_kebutuhan_perjal' :
Code In Model
function getPerjal()
{
$query=$this->db->query("SELECT * from view_kebutuhan_perjal");
return $query;
}
Code In Controller :
$Kebutuhan=$this->M_Kebutuhan_Perjal->getPerjal();
foreach ($Kebutuhan->result() as $row ) {
$hasil=array(
$row->id_perjal,
$row->jenis_perjal,
$row->ruas_jalan,
$row->lokasi_km,
$row->letak,
$row->kondisi,
$row->tahun,
$row->tahunRPJMD,
);
}
$data=array(
'data'=> [$hasil],
);
$this->output
->set_status_header(201)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($data, JSON_PRETTY_PRINT))
->_display();
exit;
But Result data just one record like bellow:-
You are over-writing $hasil variable again and again inside foreach() loop. That's why only one value is coming.Do like below:-
$hasil = array(); // create array variable
foreach ($Kebutuhan->result() as $row ) {
$hasil[]=array(
$row->id_perjal,
$row->jenis_perjal,
$row->ruas_jalan,
$row->lokasi_km,
$row->letak,
$row->kondisi,
$row->tahun,
$row->tahunRPJMD,
); // assign data to array variable
}
$data=array(
'data'=> [$hasil],
);

Check if the variables passed to a function is empty

Im working on a register function that will register users into the database.
I want a checker in that function that checks if any of the arguments are empty. I've simplified the problem, so this is not the retail look.
<?php
create_user($_POST["username"], $_POST["epost"]);
function create_user($username, $epost){
// Pull all the arguments in create_user and check if they are empty
// Instead of doing this:
if(empty($username) || empty($epost)){
}
}
Reason for making this is so i can simply add another argument to the function and it checks automatically that it isnt empty.
Shorted question:
How do I check if all the arguments in a function isnt empty?
function create_user($username, $epost){
foreach(func_get_args() as $arg)
{
//.. check the arg
}
}
You can use array_filter and array_map functions also.
For example create a function like below
<?php
function isEmpty( $items, $length ) {
$items = array_map( "trim", $items );
$items = array_filter( $items );
return ( count( $items ) !== (int)$length );
}
?>
the above function accepts two parameters.
$items = array of arguments,
$length = the number of arguments the function accepts.
you can use it like below
<?php
create_user( $_POST["username"], $_POST["epost"] );
function create_user( $username, $epost ) {
if ( isEmpty( func_get_args(), 2 ) ) {
// some arguments are empty
}
}
?>

How to pass series of variables in function as array or regardless of their order?

I am sorry, that sounds like a noob question. I am trying to do this, maybe my question is not clear.
I want to be able to pass something like this:
make_thumbnail( array( 'width' => 60, 'height' => 40', 'title' => 'my image' ) );
Now the above line calls the function which already produces the thumbnails I have that no problem, but I want flexibility here. I mean my function has variables ordered like this:
function make_thumbnail($title,$width,$height) {
the code..
echo ...
}
Now you get what I want to do? I want to be able to pass the variables in any order.. they do not have to come in same order title, width, height.. i want to be able to specify the order when I call the function in template as I put in very first line.
I tried to make my question as clear as I can, but really could not find anything about it.
This sort of thing?
function make_thumbnail($myarray) {
$sometitle = $myarray["title"]
$somewidth = $myarray["width"]
$someheight = $myarray["height"]
}
Why not have the array as the function argument? e.g.
function make_thumbnail($argsArray) {
echo $argsArray['width'];
}
You can create variables within your function for each parameter
function make_thumbnail($argsArray) {
$width = $argsArray['width'];
$height = $argsArray['height'];
$title = $argsArray['title'];
// ...plug the rest of your original function here
}
Then your function will behave exactly the same, except you can pass in an array.
What you're asking for is a description of the Reflection syntax of PHP:
function callWithNamedParams( $funcName, array $args = null )
{
if( is_null( $args ) ) return $funcName();
$f = new ReflectionFunction($funcName);
$input = array();
foreach( $f->getParameters() as $param )
{
array_push( $input, #$args[ $param->getName() ] );
}
return call_user_func_array( $funcName, $input );
}
Use:
function myFunc( $foo, $bar )
{
echo "foo = $foo; Bar = $bar";
}
callWithNamedParams( "myFunc", array( "bar"=>1, "foo"=>2 ) );
You should get foo = 2; Bar = 1 as an output.
you need to define your logic to take any parameter as the one you want it to be. Array is the best thing you can use. But changing the parameters changes the signatures.
you are kinda implementing polymorphism but in a wrong way..

Categories