I have a loop of the following kind:
foreach ($values as $key => $value) {
$attrs = array('NAME' => $key);
myproc ($attrs);
......
}
Where in myproc the first parameter is defined by reference:
function myproc (& attrs) { .... }
myproc adds the passed value to some structure.
The trouble with this is that at loop end, all the arrays added to the generated structure contains the same value, the last value extracted from the loop.
I tried also something like this :
foreach ($values as $key => $value) {
$attrs = array('NAME' => $key);
$copy = $attrs;
myproc ($copy);
......
}
but the result is the same. I'not allowed to modify the procedure. Any suggestions?
Based on the comment below your question, it seems that the problem is that you are passing a reference and this reference gets updated in the loop, leading to updates in the object you are generating in your function.
To avoid this, you need to unset the variable after the function call so that the link between the value in your object and the referenced variable is broken:
foreach ($values as $key => $value) {
$attrs = array('NAME' => $key);
myproc ($attrs);
// unset the variable so that newer values of it will have no effect
// on the object generated in `myproc`
unset($attrs);
......
}
Also see the manual.
<?php
foreach(['red','pink','green'] as $colour) {
$attrs = ['colour' => $colour];
if(colourToAction($attrs)) {
$results[] = $attrs;
}
}
var_export($results);
function colourToAction(&$attrs) {
$actions = ['red'=>'stop','amber'=>'wait', 'green' => 'go'];
if(isset($attrs['colour']) && isset($actions[$attrs['colour']])){
$attrs['action'] = $actions[$attrs['colour']];
return true;
}
}
Output:
array (
0 =>
array (
'colour' => 'red',
'action' => 'stop',
),
1 =>
array (
'colour' => 'green',
'action' => 'go',
),
)
Related
I have an array like:
$array = array(
'name' => 'Humphrey',
'email' => 'humphrey#wilkins.com
);
This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:
$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
If the second is returned, I can do a simple foreach($array as $key => $person), but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like: $person['name'] within the foreach loop.
Is there any way to make the one result believe its a multidimensional array?
Try this :
if(!is_array($array[0])) {
$new_array[] = $array;
$array = $new_array;
}
I would highly recommended making your data's structure the same regardless of how many elements are returned. It will help log terms and this will have to be done anywhere that function is called which seems like a waste.
You can check if a key exists and do some logic based on that condition.
if(array_key_exists("name", $array){
//There is one result
$array['name']; //...
} else {
//More then one
foreach($array as $k => $v){
//Do logic
}
}
You will have the keys in the first instance in the second yours keys would be the index.
Based on this, try:
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($array)){
$array[] = $array;
}
First check if the array key 'name' exists in the given array.
If it does, then it isn't a multi-dimensional array.
Here's how you can make it multi-dimensional:
if(array_key_exists("name",$array))
{
$array = array($array);
}
Now you can loop through the array assuming it's a multidimensional array.
foreach($array as $key => $person)
{
$name = $person['name'];
echo $name;
}
The reason of this is probably because you use either fetch() or fetchAll() on your db. Anyway there are solutions that uses some tricks like:
$arr = !is_array($arr[0]) ? $arr : $arr[0];
or
is_array($arr[0]) && ($arr = $arr[0]);
but there is other option with array_walk_recursive()
$array = array(
array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
$array2 = array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
);
$print = function ($item, $key) {
echo $key . $item .'<br>';
};
array_walk_recursive($array, $print);
array_walk_recursive($array2, $print);
$shortcodes['video_section'] = array(
'no_preview' => true,
'params' => 'xxx',
'shortcode' => '[sc1][/sc1]',
'popup_title' => __('Video Section', THEME_NAME),
'shortcode_icon' => __('li_video')
);
$shortcodes['image_section'] = array(
'no_preview' => true,
'params' => 'yyy',
'shortcode' => '[sc2][/sc2]',
'popup_title' => __('Image Section', THEME_NAME),
'shortcode_icon' => __('li_image')
);
$shortcodes[] = $th_shortcodes;
How can I retrieve the name of each array and then access to the key and value:
for example I need to loop throught $shortcode and get the array main name: 'image_section' 'video_section'
Then to retrieve the value of some key. I know how to retrieve key and value but really don't understand how to get the name of the declared array. If i do: var_dump($value); I saw the name of the array but how to access to it?
You can use foreach
foreach($shortcodes as $key => $value) {
echo $key // echoes "vide_section" and "image_section"
foreach($value as $innerKey => $innerValue) {
echo $innerKey // echoes 'no_preview', 'params', 'shortcode', 'popup_title', 'shortcode_icon' twice
}
}
Note that $value in this case refers to arrays, you can foreach again to access the inner values.
Use the array_flip function on the array
$array = array_flip($shortcodes);
Yes you can use foreach, where it goes through each item on array, based on creation order.
foreach($shortcodes as $key => $value) {
// $key represents video_section for 1st iteration and image_section for 2nd.
//Here each are array, so you can again iterate over $value and get each item .
foreach($value as $key2 => $value2) {
//here keys are no_preview, params and so on on subsequent iterations.
}
}
There's array_keys():
$keynames = array_keys($shortcodes);
You could foreach throught it:
foreach($shortcodes as $key=>values){ echo $key; }
or flip the values with the case (though this last one I don't recommend), and than foreach through those. But array flip is best to be left alone in this case (though I nice function to keep in the back of your head).
I'm trying to remove an object from an array of objects by its' index. Here's what I've got so far, but i'm stumped.
$index = 2;
$objectarray = array(
0=>array('label'=>'foo', 'value'=>'n23'),
1=>array('label'=>'bar', 'value'=>'2n13'),
2=>array('label'=>'foobar', 'value'=>'n2314'),
3=>array('label'=>'barfoo', 'value'=>'03n23')
);
//I've tried the following but it removes the entire array.
foreach ($objectarray as $key => $object) {
if ($key == $index) {
array_splice($object, $key, 1);
//unset($object[$key]); also removes entire array.
}
}
Any help would be appreciated.
Updated Solution
array_splice($objectarray, $index, 1); //array_splice accepts 3 parameters
//(array, start, length) removes the given array and then normalizes the index
//OR
unset($objectarray[$index]); //removes the array at given index
$reindex = array_values($objectarray); //normalize index
$objectarray = $reindex; //update variable
array_splice($objectarray, $index, 1);
//array_splice accepts 3 parameters (array, start, length) and removes the given
//array and then normalizes the index
//OR
unset($objectarray[$index]); //removes the array at given index
$reindex = array_values($objectarray); //normalize index
$objectarray = $reindex; //update variable
You have to use the function unset on your array.
So its like that:
<?php
$index = 2;
$objectarray = array(
0 => array('label' => 'foo', 'value' => 'n23'),
1 => array('label' => 'bar', 'value' => '2n13'),
2 => array('label' => 'foobar', 'value' => 'n2314'),
3 => array('label' => 'barfoo', 'value' => '03n23')
);
var_dump($objectarray);
foreach ($objectarray as $key => $object) {
if ($key == $index) {
unset($objectarray[$index]);
}
}
var_dump($objectarray);
?>
Remember, your array will have odd indexes after that and you must (if you want) reindex it.
$foo2 = array_values($objectarray);
in that case you won't need that foreach just unset directly
unset($objectarray[$index]);
I've got this error Warning: strtolower() expects parameter 1 to be string, array given..
I don't know how I've got my error.. Please help thanks!
$mypages = array(
'Pages' => array('page' => array('view_all_pages', 'add_page', 'dashboard'),
'test' => array('test1', 'test2')),
'Users' => array('vieW_all_users', 'add_user'));
foreach($mypages as $keys => $key):
if(is_array($key)):
$key = array_map('strtolower' ,$key);
endif;
endforeach;
foreach is a loop that will gives you first level of key=>value pairs of an array.
foreach($mypages as $keys => $key){
echo "Key : $keys \n";
echo "Value : ";var_dump($key);
}
will output :
Key : Pages
Value : array('page' => array('view_all_pages', 'add_page', 'dashboard'), 'test'=> array('test1', 'test2')),
Key : Users
Value : array('vieW_all_users', 'add_user')
To make it work, you need to check if the value is an array.
function strtolowerArray(&$arr){
foreach($arr as $k=>$v){
if(is_array($v)){
$arr[$k] = strtolowerArray($v);
}
else if(is_string($v)){
$arr[$k] = strtolower($v);
}
else{
throw new \LogicException("The value is neither a string nor an array");
}
}
return $arr;
}
$mypages = array(
'Pages' => array(
'page' => array('view_ALL_pages', 'aDD_page', 'DaShbOArd'),
'test' => array('test1', 'TEST2')
),
'Users' => array('vieW_all_users', 'aDd_uSer')
);
var_dump(strtolowerArray($mypages));
The '&' in front of the strtolowerArray's parameter means we pass teh variable by reference. If anychanges happens to this variables inside strtolowerArray function's scope, then it will be reflected into the parent scope.
$mypages['Pages']['page'] does not contain a string that can be passed to strtolower().
You should debug by dumping $key inside the loop.
You have arrays in your arrays yo!
You have to iterate into the arrays before asking for (and trying to convert) the values.
Try walking through the array conditionally e.g.
//pseudo
func myRecursion($data = array()) {
foreach($data as $value) {
if(is_array($value)) {
$data = myRecusion($data[$value]);
} else {
//its not an array so do your thing
}
}
return($data);
}
I have a function like the below one that will select from the DB some different values.
One of these values needs to be edited before passing the array to other functions.
The problem is that I don't know how to return the array with the edited element. How can I edit a value in the array and return the full array but with the edited element?
function eGetDashboard($eID, $pdo) {
$dashboard = PDOjoin('event', 'event.*, join_category_event.*, join_event_user.*, _dashboard.*, _dashboard_icons.*', array(
array('LEFT JOIN' => 'join_category_event', 'ON' => 'event.id_event = join_category_event.id_event'),
array('LEFT JOIN' => 'join_event_user', 'ON' => 'event.id_event = join_event_user.id_event'),
array('LEFT JOIN' => '_dashboard', 'ON' => 'join_category_event.id_category = _dashboard.id_category'),
array('LEFT JOIN' => '_dashboard_icons', 'ON' => 'join_category_event.id_category = _dashboard_icons.id_category')
), array('event.id_event' => $eID), $pdo);
foreach ($dashboard as $eDashboard)
$label = eSetDashboardLabel($eDashboard['multimedia_descr'], getLang());
return $dashboard;
}
function eSetDashboardLabel($label, $lang) {
$label = explode(";", $label);
foreach ($label as $labels) {
if (substr($labels, 1, 2) == $lang)
return substr($labels, 4);
}
}
By using a Reference (note: &) to the element, any changes will affect the original element:
foreach ($dashboard as &$eDashboard) {
$eDashboard['multimedia_descr'] = eSetDashboardLabel($eDashboard['multimedia_descr'], getLang());
}
Alternatively, you can capture the key in the loop and reference the array:
foreach ($dashboard as $key => $eDashboard) {
$dashboard[$key]['multimedia_descr'] = eSetDashboardLabel($eDashboard['multimedia_descr'], getLang());
}