How to do an array merge between two functions? - php

I'm trying to get an array_merge but I can't. Calling the example.php file must also embed the array of the Usage_Module function.
Note: The getFunctionModule function must not be changed.
Surely I'm wrong something in the Usage_Module function, can you help me understand what I'm wrong?
Code example.php
function getFunctionModule() {
require "module.php";
$func = "Usage_Module";
if (!function_exists($func)) {
echo "function not found";
}
return (array) $func();
}
$data = ['status' => 'ok'];
$data = array_merge(getFunctionModule(), $data);
print_r($data);
Code module.php
function Usage_Module()
{
$data = ['licensekey2' => 'ok'];
return (array) $data;
}

Related

Call a function within a function display both within array

how do I call a function from within a function?
function tt($data,$s,$t){
$data=$data;
echo '[[';
print_r($data);
echo ']]';
if($t==0){
$data[]=$s;
tt($data,'two',1);
}else{
$data[]=$s;
}
return $data;
}
print_r(tt('','one',0));
I want 'two' to be shown within the array like
$o[]='one';
$o[]='two';
print_r($o);
function tt($s, $t, array $data = array()) {
$data[] = $s;
if ($t == 0) {
$data = tt('two', 1, $data);
}
return $data;
}
print_r(tt('one', 0));
This is all that's really needed.
Put the array as the last argument and make it optional, because you don't need it on the initial call.
When calling tt recursively, you need to "catch" its return data, otherwise the recursive call simply does nothing of lasting value.
No need for the else, since you're going to append the entry to the array no matter what and don't need to write that twice.
Try this one (notice the function signature, the array is passed by ref &$data):
function tt(&$data,$s,$t){
echo '[[';
print_r($data);
echo ']]';
if($t==0){
$data[]=$s;
tt($data,'two',1);
}else{
$data[]=$s;
}
return $data;
}
$array = [];
tt($array,'one',0);
print_r($array);
/**
Array
(
[0] => one
[1] => two
)
*/
try this
function tt($data,$s,$t){
global $data;
if($t==0){
$data[]=$s;
tt($data,'two',1);
}else{
$data[]=$s;
}
return $data;
}
print_r(tt('','one',0));
OUTPUT :
Array
(
[0] => one
[1] => two
)
DEMO

Recursive function with unknown depth of values. Return all values (undefined depth)

I have a question about a recursive PHP function.
I have an array of ID’s and a function, returning an array of „child id’s“ for the given id.
public function getChildId($id) {
…
//do some stuff in db
…
return childids;
}
One childid can have childids, too!
Now, I want to have an recursive function, collecting all the childids.
I have an array with ids like this:
$myIds = array("1111“,"2222“,"3333“,“4444“,…);
and a funktion:
function getAll($myIds) {
}
What I want: I want an array, containing all the id’s (including an unknown level of childids) on the same level of my array. As long as the getChildId($id)-function is returning ID’s…
I started with my function like this:
function getAll($myIds) {
$allIds = $myIds;
foreach($myIds as $mId) {
$childids = getChildId($mId);
foreach($childids as $sId) {
array_push($allIds, $sId);
//here is my problem.
//what do I have to do, to make this function rekursive to
//search for all the childids?
}
}
return $allIds;
}
I tried a lot of things, but nothing worked. Can you help me?
Assuming a flat array as in your example, you simply need to call a function that checks each array element to determine if its an array. If it is, the function calls it itself, if not the array element is appended to a result array. Here's an example:
$foo = array(1,2,3,
array(4,5,
array(6,7,
array(8,9,10)
)
),
11,12
);
$bar = array();
recurse($foo,$bar);
function recurse($a,&$bar){
foreach($a as $e){
if(is_array($e)){
recurse($e,$bar);
}else{
$bar[] = $e;
}
}
}
var_dump($bar);
DEMO
I think this code should do the trick
function getAll($myIds) {
$allIds = Array();
foreach($myIds as $mId) {
array_push($allIds, $mId);
$subids = getSubId($mId);
foreach($subids as $sId) {
$nestedIds = getAll($sId);
$allIds = array_merge($allIds, $nestedIds);
}
}
return $allIds;
}

PhP Associative Array displayed in a Table

I am VERY new to PhP. Quick question that I am having trouble finding the answer to online, although I am sure most of you will quickly know the answer. I have the following code creating an associative array and then I am trying to display it in a table. I know there are easier ways to display it in a table like a foreach loop, but I would like to learn this method first :
class CarDealer extends Company {
var $navbar_array = array();
function create_navbar_array ( ) {
$mainurl = $this->company_url; // get the main url address of this web page
$this->navbar_array = array( "Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact" );
}
function getLeftNavBar() {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
$data .="<tr><td>$this->navbar_array['Home Page']</td></tr>";
$data .="<tr><td>$this->navbar_array['Sales']</td></tr>";
$data .="<tr><td>$this->navbar_array['Support']</td></tr>";
$data .="<tr><td>$this->navbar_array['Contacts']</td></tr>";
$data .="</table>";
return $data;
}
}
Later in my code I create an object for my class and then try to print the table. Unfortunately I am just getting an output of things like Array['Home Page'].
$carobject = new CarDealer();
$carobject->create_navbar_array();
print $carobject->getLeftNavBar();
you need to pass array values to the function try
class extends Company {
var $navbar_array = array();
function create_navbar_array ( ) {
$mainurl = $this->company_url; // get the main url address of this web page
$this->navbar_array = array( "Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact" );
return $this->navbar_array;
}
function getLeftNavBar($arr) {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
$data .="<tr><td>".$arr['Home Page']."</td></tr>";
$data .="<tr><td>".$arr['Sales']."</td></tr>";
$data .="<tr><td>".$arr['Support']."</td></tr>";
$data .="<tr><td>".$arr['Contacts']."</td></tr>";
$data .="</table>";
return $data;
}
}
$carobject = new CarDealer();
$arr = $carobject->create_navbar_array();
print $carobject->getLeftNavBar($arr);
or need to make public your array
public $navbar_array = array();
before return $data;, print_r($data); so you can know the associative array's structure. If it didnt print on the page, try looking in view-page-source. You'll get an clear picture. I think $data should be an array, so prob it should be like
$data['someField'] = $someValues;
And, Create or define the array before you use them.
You need to concatenate the array values inside the getLeftNavBar() method so php knows to parse them.
try
$data .="<tr><td>{ $this->navbar_array['Home Page'] }</td></tr>";
or
$data .="<tr><td>".$this->navbar_array['Sales']."</td></tr>";
Why not just call create_navbar_array() inside getLeftNavBar()
function getLeftNavBar() {
$this->create_navbar_array();
.....
You could rewrite it like this
class CarDealer {
private function getUrls() {
return array(
"Home Page" => "$this->company_url?whichpage=home",
"Sales" => "$this->company_url?whichpage=sales",
"Support" => "$this->company_url?whichpage=support",
"Contacts" => "$this->company_url?whichpage=contact"
);
}
public function getLeftNavBar() {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
foreach($this->getUrls() as $url ) {
$data .="<tr><td>".$url."</td></tr>";
}
return $data . "</table>";
}
}
$carobject = new CarDealer();
print $carobject->getLeftNavBar();

php pass array to function as separate variables

i need to know how to pass an array to a function as separate variables, for instance,
function myfunction($var, $othervar) {
}
$myarray = array('key'=>'val', 'data'=>'pair');
here is where I am running into problems, the following doesn't seem to work:
$return = myfunction(extract($myarray));
it should, if I understand correctly, basically be the same as
$return = myfunction($key, $data);
where $key='val' and $data='pair'
can anyone please explain this to me.
If I am understanding your question right then try this
$return = myfunction($myarray["key"],$myarray["data"]);
here we are simply passing the associative array as arguments.
public function get($key=null, $function='', array $vars=array()) {
if ($key==null || !array_key_exists($key, $this->_obj)) {
return null;
}
var_dump($vars);
if (!empty($function)) {
return $this->_obj[$key]->$function(array_walk($vars));
// return call_user_func_array(array(get_class($this->_obj[$key]), $function), $vars);
// return $this->_obj[$key]->$function(extract($vars));
}
return $this->_obj[$key];
}
public function get($key=null, $function='', array $vars=array()) {
if ($key==null || !array_key_exists($key, $this->_obj)) {
return null;
}
if (!empty($function)) {
return call_user_func_array(array($this->_obj[$key], $function), $vars);
}
return $this->_obj[$key];
}
$registry = Registry_Object::Singleton();
//...later on
$registry = $GLOBALS['registry'];
$registry->set('Content', new Content($_SERVER['REQUEST_URI']));
$id = $registry->get('Content', 'GetIdFunc');
$registry->set('DB', 'Database');
$query = $registry->get('DB', 'Read', array("SELECT TITLE, CONTENT FROM APP_CONTENT WHERE ID=$id"));
print '<h1>'.$query[0]['TITLE'].'</h1>';
print Template_Helper::TPL_Paragraphs($query[0]['CONTENT']);
thanks all

PHP: Return the last json object

Edit
Thanks for all the input on this, I did find error in my question so modifying now. Sorry for that.
I am trying to figure out how to return the last object in the JSON string I have rendered. The two functions I am working with:
public function revision($return = false)
{
$id = $this->input->post('galleryID');
$data = array('revision_count' => $this->revision->count_revision($id) );
if($return){
return json_encode($data);
}
else {
echo json_encode($data);
}
}
public function last_revision()
{
$allRevisions = json_decode($this->revision(),true);
return end($allRevisions);
}
The issue is that end() returns error stating that 1st parameter should be array.
Thanks for any help on this.
It is important to note here that json_decode returns an instance of stdClass by default. Try using json_decode($jsonstring, true) to return the JSON as a PHP associative array.
However, You haven't included what the $this->revision() method does. Could you possibly show that portion of the code, since that is the function you are getting a return value from?
Edit:
Alright, after we saw the right function in your code, here are a couple of things I would like to say:
You have added a $return parameter to your revision method, but you aren't using it when you need to. You should change $this->revision() to $this->revision(true) in your last_revision method.
If you're going to return data from the revision() method, there's not much of a point in json_encodeing it, just to json_decode the result. Just pass back the raw data array.
Once you have changed both of these things, this should work:
$allRevisions = $this->revision(true); return end($allRevisions['revision_count']);
You can change the edit_function() to:
public function edit_revision($return = false)
{
$galleryID = $this->input->post('galleryID');
$revisionID = $this->input->post('revisionID');
$data = array('revision_images' => $this->revision->get($galleryID, $revisionID) );
if($return)
return json_encode($data);
else
echo json_encode($data);
}
and then:
public function last_revision(true)
{
$allRevisions = json_decode($this->revision());
return end($allRevisions);
}
Maybe you need convert that json output to an php array (json_decode() function), then you could get the last item with array_pop() function:
https://php.net/array_pop

Categories