I have no idea why this keeps returning false.
The best part is at the echo statements it actually echo's. This function is in a plugin that I am writing for WordPress.
function find_field($field_name,$array) {
if(array_key_exists($field_name,$array)) {
echo 'Here';
echo $array[$field_name];
return $array[$field_name];
}
foreach($array as $value) {
if(is_array($value)) {
find_field($field_name,$value);
}
}
return false;
}
If I run this: echo find_field('cellphone_number',$arr);
And this is my $arr:
array(
'page' => 'wp_crm_add_new',
'wp_crm' => array(
'user_data' => array(
'user_id' => array(
(int) 0 => array(
'value' => ''
)
),
'user_pass' => array(
(int) 1428 => array(
'value' => ''
)
),
'role' => array(
(int) 2718 => array(
'value' => ''
)
),
'display_name' => array(
(int) 14454 => array(
'value' => 'Albert'
)
),
'user_email' => array(
(int) 26059 => array(
'value' => 'albert#domain.com'
)
),
'company' => array(
(int) 85772 => array(
'value' => ''
)
),
'cellphone_number' => array(
(int) 62506 => array(
'value' => '0820000000'
)
),
'last_visit' => array(
(int) 45073 => array(
'value' => ''
)
)
)
),
'meta-box-order-nonce' => '1374268beb',
'closedpostboxesnonce' => '92fffdd685',
'wp_crm_update_user' => '42d35393d7',
'show_admin_bar_front' => 'false',
'color-nonce' => 'c02f4b0a88',
'admin_color' => 'sunrise',
'original_publish' => 'Publish',
'publish' => 'Save'
)
I get false as the result, every time. What am I doing wrong?
This is happening because you return false. Here's the logic break-down:
function find_field($field_name,$array) {
if(SOMETHING) {
DO SOMETHING
return SOMETHING;
}
foreach($array as $value) {
if(SOMETHING) {
CALL RECURSIVE FUNCTION
}
}
return false;
}
Put like this... if you call the function at any point and send a value that passes the first if statement, then you return a value. If you do not pass that if statement (aka the array_key doesn't exist) then you move into a foreach loop, which does some stuff, calls a recursive function which eventually returns a value (and does nothing with it) before moving on to the final line of code... return false.
It is important to first think of a recursive function as a one-time function before compounding it into a recursive one.
Just like any other function, this recursive function is going to execute every line of code (although interrupted) before it is done. The last line of code you execute is always a "return false" which is throwing your result.
Perhaps you should be returning the inner foreach loop value when you call the recursive function:
function find_field($field_name,$array) {
if(array_key_exists($field_name,$array)) {
echo 'Here';
echo $array[$field_name];
return $array[$field_name];
}
foreach($array as $value) {
if(is_array($value)) {
return find_field($field_name,$value);
}
}
return false;
}
Related
I have the following multidimensional array that is obtained through an API.
$exchangeID = array(
0 => array(
'id' => 'vcxz',
'currency' => 'GBP',
),
1 => array(
'id' => 'mnbv',
'currency' => 'EUR',
),
2 => array(
'id' => 'lkjh',
'currency' => 'USD',
),
3 => array(
'id' => 'poiuy',
'currency' => 'KRN',
),
);
I would like to obtain the id of USD which is lkjh. I know this can be obtained by simply doing $exchangeID[2]['id']. The problem is that the array is dynamic. For example when it is loaded the first subarray may be EUR instead of GBP, and the third subarray may be KRN instead of USD.
Basically, what I have in mind is to look for the subarray where there is the currency first, then accordingly find the corresponding id. E.g. if I want to find EUR. First I find the EUR, then get 'mnbv'.
I tried this $key = array_search('USD', array_column($exchangeID, 'currency')); but I got the following error in my error_log PHP Fatal error: Call to undefined function array_column() to get at least the array number e.g. in this case 2.
You can simply filter your array, like this:
$usd_exchanges = array_filter($exchangeID, function($row) {
return $row['currency'] == "USD";
}));
var_dump($usd_exchanges[0]);
You can also return the first element of the filter, using the current method:
$usd_exchange = current(array_filter($exchangeID, function($row) {
return $row['currency'] == "USD";
})));
var_dump($usd_exchange);
Try this:
foreach ($exchangeID as $key => $arr)
if($arr['currency'] == 'USD')
echo $key;
It is possible to use following custom function to get the key:
echo getKeyRecursive('USD', $exchangeID);
function getKeyRecursive($needle, $haystack, $strict = false)
{
foreach ($haystack as $key => $item){
if(($strict ? $item === $needle : $item == $needle) || (is_array($item) && getKeyRecursive($needle, $item, $strict))) return $key;
}
return false;
}
foreach($exchangeID as $key=>$value)
{
if($exchangeID[$key]['currency']=='USD'){
$usdId=$exchangeID[$key]['id'];
break;
}
}
//echo $usdId;
//Result:ikjh
<?php
$exchangeID = array(
0 => array(
'id' => 'vcxz',
'currency' => 'GBP',
),
1 => array(
'id' => 'mnbv',
'currency' => 'EUR',
),
2 => array(
'id' => 'lkjh',
'currency' => 'USD',
),
3 => array(
'id' => 'poiuy',
'currency' => 'KRN',
),
);
$db=new PDO('sqlite::memory:','','',array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$db->query('CREATE TABLE `troll` (`dbid` TEXT, `dbcurrency` TEXT);');
$stm=$db->prepare("INSERT INTO `troll` (`dbid`,`dbcurrency`) VALUES(:id,:currency);");
array_walk($exchangeID,function($arr)use($stm){$stm->execute($arr);});
$res=$db->query("SELECT `dbid` AS `id` FROM `troll` WHERE `dbcurrency` = ".$db->quote('USD').' LIMIT 1');
$id=$res->fetch(PDO::FETCH_ASSOC);
$id=$id['id'];
var_dump($id);
see working example here http://codepad.viper-7.com/1lg2Gj
Try this if this works:
foreach($exchangeID as $key => $val)
{
if(array_key_exists('currency', $val))
if($val['currency'] == 'USD'){
echo $val['id'];
echo $val['currency'];
elseif($val['currency'] == 'GBP'){a1
echo $val['id'];
echo $val['currency']);
elseif($val['currency'] == 'EUR'){
echo $val['id'];
echo $val['currency'];
}else{
echo $val['id'];
echo $val['currency'];
}
}
}
first of, just wanted to let you know that I am a newbie at CI. but I am having trouble with this piece of code where is breaking and I can't seem to be able to find the answer anywhere.
for some reason the code is breaking at the first if statement.. if possible could you help me out understand what is really happening there?
Thank you all for your help!
function main
{
$this->load->model(getData) psudo code for this area...
}
---model---
function getData....
{
Sql = this->db->query(sql code that returns all the information required.)
$result = $sql->result_array();
$types = array ( 'EVENT|TIME' => array( 'id' => 1, 'name' => 'Regular' ),
'PROPOSITION|REGULAR' => array( 'id' => 2, 'name' =>'Propositions'),
'EVENT|TIME' => array( 'id' => 3, 'name' => 'Now' ),
'PROPOSITION|FUTURES' => array( 'id' => 4, 'name' => 'Future' ));
$var = array();
foreach ($result as $event) {
$cat = $event['type'] . '|' . $event['sub_type'];
$typeId = $types[$cat]['id'];
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))
{
if(!is_array($var[$event['event_id']]))
{
$var[$event['event_id']] = array( 'event_name' =>
$event['event_name'],'event_abbreviation' =>
$event['event_abbreviation']);
}
$var[$event['event_id']]['var'][$event['type_id']] = array(
'type_name' => $event['abbreviation'],'type_abbreviation' => $event['name']
);
}
$event[$event['event_id']]['var'][$event['type_id']]['types'][$typeId] =
$types[$cat]['name'];
}
return $myResults;
}
In this line
if(!is_array($var[$event['event_id']]['var']$event['type_id']]))
You are missing a [ somewhere. I'm guessing before $event['type_id'].
So replace with:
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))
So I am building off of this question about multidimensional associative array of arrays. and what I came up with is a really simple and easy way to solve my problem. The following array:
$options = array(
'navigation' => array(
'page_title' => __('Aisis', 'aisis'),
'menu_title' => __('Aisis', 'aisis'),
'capabillity' => 'edit_themes',
'menu_slug' => 'aisis-core-options',
'function' => 'some_function',
'icon_url' => '',
'position' => '',
'sub_menues' => array(
array(
'page_title' => __('Aisis', 'aisis'),
'menu_title' => __('Aisis', 'aisis'),
'capabillity' => 'edit_themes',
'menu_slug' => 'aisis-core-options',
'function' => 'some_function',
),
array(
'page_title' => __('Aisis', 'aisis'),
'menu_title' => __('Aisis', 'aisis'),
'capabillity' => 'edit_themes',
'menu_slug' => 'aisis-core-options',
'function' => 'some_function',
),
)
),
'settings' => array(
array(
'option_group' => 'bla',
'option_name' => '',
'sanitize_call_back' => ''
)
),
'core_template' => 'path/to/admin/template.phtml'
);
Is then processed as such:
foreach($options as $settings=>$option){
if($setting = 'navigation' && is_array($option)){
foreach($option as $option_key=>$option_value){
var_dump($option);
if(!is_array($option_value)){
echo implode(',', $option);
}
}
}
}
The problem is:
in the last if statement I am stating, or at least I think I am, as long as the value for the key in the $options['navigation'] is NOT an array, implode the array and return the values. It all works as expected, accept it gives me "Array to string conversion" which it "shouldn't" due to the if statement.
So my simple question is:
How do I implode $options['navigation'] as long as the value of a key is not an array?
I thought I was on the right track....
Also, on that note, when I var_dump($option_values) I see the other arrays, so not only do I see 'sub_menues' but I also see 'settings' array
I thought my logic was sound with:
if the key is navigation, do this.
Essentially I am having a scope issue with arrays in this case, so how do I make it ONLY look at the key => values and any additional arrays with in the $options['navigation'] instead of with in $options?
Use == instead of = to compare values.
EDIT: That said, why are you using a foreach if you're only interested in one key?
if( is_array($options['navigation'])) {
foreach($options['navigation'] as $value) {
if( is_array($value)) echo implode(",",$value);
}
}
Correct solution building off of Kolink's solution:
$temp_array = array();
if( is_array($options['navigation'])) {
foreach($options['navigation'] as $value) {
if(!is_array($value)){
$temp_array[] = $value;
}
}
echo implode(',', $temp_array);
}
Well, I am here again dealing with arrays in php. I need your hand to guide me in the right direction. Suppose the following array:
-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98
The - (hyphen) symbol only illustrates the deep level.
Well, I need to build another array (or whatever), because it should be printed as an HTML select as below:
-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98
Looks that for each level element, it should add a space, or hyphen to determinate that it belongs to a particular parent.
EDIT
The have provide an answer provideng my final code. The html select element will display each level as string (repeating the "-" at the begging of the text instead multi-level elements.
Here's a simple recursive function to build a select dropdown given an array. Unfortunately I'm not able to test it, but let me know if it works. Usage would be as follows:
function generateDropdown($array, $level = 1)
{
if ($level == 1)
{
$menu = '<select>';
}
foreach ($array as $a)
{
if (is_array($a))
{
$menu .= generateDropdown($a, $level+1);
}
else
{
$menu .= '<option>'.str_pad('',$level,'-').$a.'</option>'."\n";
}
}
if ($level == 1)
{
$menu = '</select>';
}
return $menu;
}
OK, I got it with the help of #jmgardhn2.
The data
This is my array:
$temp = array(
array(
'name' => 'fruits',
'sons' => array(
array(
'name' => 'green',
'sons' => array(
array(
'name' => 'mango'
),
array(
'name' => 'banana',
)
)
)
)
),
array(
'name' => 'cars',
'sons' => array(
array(
'name' => 'italy',
'sons' => array(
array(
'name' => 'ferrari',
'sons' => array(
array(
'name' => 'red'
),
array(
'name' => 'black'
),
)
),
array(
'name' => 'fiat',
)
)
),
array(
'name' => 'germany',
'sons' => array(
array(
'name' => 'bmw',
)
)
),
)
)
);
Recursive function
Now, the following function will provide an array with items like [level] => [name]:
function createSelect($tree, $items, $level)
{
foreach ($tree as $key)
{
if (is_array($key))
{
$items = createSelect($key, $items, $level + 1);
}
else
{
$items[] = array('level' => $level, 'text' => $key);
}
}
return $items;
}
Calling the funcion
Now, call the function as below:
$items = createSelect($temp, array(), 0);
Output
If you iterate the final $items array it will look like:
1fruits
2green
3mango
3banana
1cars
2italy
3ferrari
4red
4black
3fiat
2germany
3bmw
$array = array(
array(
'id' => 1,
'name' => 'John Doe',
'upline' => 0
),
array(
'id' => 2,
'name' => 'Jerry Maxwell',
'upline' => 1
),
array(
'id' => 3,
'name' => 'Roseann Solano',
'upline' => 1
),
array(
'id' => 4,
'name' => 'Joshua Doe',
'upline' => 1
),
array(
'id' => 5,
'name' => 'Ford Maxwell',
'upline' => 1
),
array(
'id' => 6,
'name' => 'Ryan Solano',
'upline' => 1
),
array(
'id' =>7,
'name' => 'John Mayer',
'upline' => 3
),
);
I want to make a function like:
function get_downline($userid,$users_array){
}
Then i want to return an array of all the user's upline key with the value as $userid. I hope anyone can help. Please please...
You could do it with a simple loop, but let's use this opportunity to demonstrate PHP 5.3 anonymous functions:
function get_downline($id, array $array) {
return array_filter($array, function ($i) use ($id) { return $i['upline'] == $id; });
}
BTW, I have no idea if this is what you want, since your question isn't very clear.
If you need do search thru yours array by $id:
foreach($array as $value)
{
$user_id = $value["id"];
$userName = $value["name"];
$some_key++;
$users_array[$user_id] = array("name" => $userName, "upline" => '1');
}
function get_downline($user_id, $users_array){
foreach($users_array as $key => $value)
{
if($key == $user_id)
{
echo $value["name"];
...do something else.....
}
}
}
or to search by 'upline':
function get_downline($search_upline, $users_array){
foreach($users_array as $key => $value)
{
$user_upline = $value["upline"];
if($user_upline == $search_upline)
{
echo $value["name"];
...do something else.....
}
}
}
Code :
function get_downline($userid,$users_array)
{
$result = array();
foreach ($users_array as $user)
{
if ($user['id']==$userid)
$result[] = $user['upline'];
}
return result;
}
?>
Example Usage :
get_downline(4,$array);