I always have trouble wrapping my head around these foreach array things, and SO has been an incredibly value resource in getting me there, so I hope you guys can help with this one.
public function progress_bar()
{
$items = array(
array(
'step-name' => 'Setup',
'url' => '/projects/new/setup/',
),
array(
'step-name' => 'Artwork',
'url' => '/projects/new/artwork/',
),
array(
'step-name' => 'Review',
'url' => '/projects/new/review/',
),
array(
'step-name' => 'Shipping',
'url' => '/projects/new/shipping-info/',
),
array(
'step-name' => 'Billing',
'url' => '/projects/new/billing/',
),
array(
'step-name' => 'Receipt',
'url' => '/projects/new/receipt/',
),
);
// Status can be active, editing, or complete.
foreach ($this->progress as $step => $status)
{
foreach ($items as $item)
{
$item['step-name'] == ucfirst($step) ? $item['status'] = $status : '';
}
}
return $items;
}
$this->progress contains an array of statuses ('setup' => 'active', 'artwork' => 'editing')
I want to add to the $items array the status of each matching item in $this->progress
$items = array(
array(
'step-name' => 'Setup',
'url' => '/projects/new/setup',
'status' => 'active',
),
etc...
);
If I understand your question correctly, the problem is that you are trying to add an array element to $items, but what you're actually doing is adding the element to a temporary variable ($item), which does not reference the original $items variable.
I'd suggest approaching it like this:
foreach ($this->progress as $step => $status)
{
// Having the $key here allows us to reference the
// original $items variable.
foreach ($items as $key => $item)
{
if ($item['step-name'] == ucfirst($step) )
{
$items[$key]['status'] = $status;
}
}
}
return $items;
Are you locked into using an array to store $items? If so, you're going to be stuck doing a nested loop ("For each element in $this->progress, check each element in $items. If match, update $items" or something like that). If you have some flexibility, I would use a hash for $items (associative array in php-speak), where the index is the step name. So $items['Setup'] would contain 'url' => ... and 'status' => ... etc. Does that make sense? Then your algorithm breaks down to "For each element in $this->progress, get the element in $items by name ($items[$step_name]) and update it's info."
I would change how you have the $items array keyed and do it like this. Stops you from having the nested loops.
public function progress_bar()
{
$items = array(
'Setup' => array(
'url' => '/projects/new/setup/',
),
'Artwork' => array(
'url' => '/projects/new/artwork/',
),
'Review' => array(
'url' => '/projects/new/review/',
),
'Shipping' => array(
'url' => '/projects/new/shipping-info/',
),
'Billing' => array(
'url' => '/projects/new/billing/',
),
'Receipt' => array(
'url' => '/projects/new/receipt/',
)
);
// Status can be active, editing, or complete.
foreach ($this->progress as $step => $status)
{
$item[ucfirst($step)]['status'] = $status;
}
return $items;
}
Related
Consider the following array:
$serviceNames = array(
0 => array(
'language' => 'en',
'value' => 'something',
'type' => 'name',
),
1 => array(
'language' => 'fi',
'value' => 'jotain',
'type' => 'name',
),
2 => array(
'language' => 'sv',
'value' => 'någonting',
'type' => 'name',
),
);
I need to get the 'value' definitions based on language. The problematic part is that the array $serviceNames does not have a predefined length (comes originally as a JSON file from an API), and the items can come in any order (in my example it goes like en, fi, sv, but it could be de, en, sv, fr... you get it).
If I wanted to get 'value' within the array where 'language' equals to 'en', how could I do that?
My advice is that you make the array associative.
Once that is done you access the value by ["language"]["value"].
$serviceNames = array_column($serviceNames, Null, "language");
echo $serviceNames["fi"]["value"]; //jotain
echo $serviceNames["en"]["value"]; //something
echo $serviceNames["sv"]["value"]; //någonting
https://3v4l.org/ssGQa
You can array_search() and array_column() function. first find the key where "en" is in the array then get the value.
$key = array_search('en', array_column($serviceNames, 'language'));
echo $serviceNames[$key]['value'];
Demo
simple:
$serviceNames = array(
0 => array(
'language' => 'en',
'value' => 'something',
'type' => 'name',
),
1 => array(
'language' => 'fi',
'value' => 'jotain',
'type' => 'name',
),
2 => array(
'language' => 'sv',
'value' => 'någonting',
'type' => 'name',
),
);
function myfunction(array $serviceNames, $field)
{
foreach($serviceNames as $service)
{
if ( $service['language'] === $field )
return $service['value'];
}
return false;
}
echo myfunction($serviceNames, 'en');
Output will : something
you would have to go through each elements of the array, using the foreach statement.
something like:
function getValueForLang($lang, array $arr)
{
foreach ($arr as $desc) {
if ($desc['language'] == $lang) {
return $arr['value'];
}
}
return null;
}
getValueForLang('en', $serviceNames); // gets your value, null if not found
see also:
https://secure.php.net/manual/en/control-structures.foreach.php
I have an array like this:
return array(
'User Management -> Role Management' => array(
array(
'permission' => 'role-management.view',
'label' => 'View',
),
array(
'permission' => 'role-management.create',
'label' => 'Create',
),
array(
'permission' => 'role-management.edit',
'label' => 'Edit',
),
array(
'permission' => 'role-management.delete',
'label' => 'Delete',
),
),
'User Management -> User Management' => array(
array(
'permission' => 'user-management.view',
'label' => 'View',
),
array(
'permission' => 'user-management.create',
'label' => 'Create',
),
array(
'permission' => 'user-management.edit',
'label' => 'Edit',
),
array(
'permission' => 'user-management.delete',
'label' => 'Delete',
),
),
);
I have accessed this array successfully like this:
$permissions = Config::get('permissions');
I want to add new index below label. I have tried this but could not add.
`foreach ($permissions as $permission) {
foreach ($permission as $eachPermission) {
$encodedPermission = base64_encode($eachPermission['permission']);
// $eachPermission['encodedPermission'] = $encodedPermission;
array_push($eachPermission, "encodedPermission", $encodedPermission);
}
}
var_dump($permissions); `
I have tried these but could not set the new index. My expected result was this:
'permission' => 'role-management.view',
'label' => 'View',
'encodedPermission' => 'someencodedstring'
Am I doing it wrong or missing something.
Your array is multi-level, so you need to do double-foreach to reach the level required for your changes.
And for your changes being saved in the original array, you need to use ampersand (&) before your iterators to keep the reference to the original array. Without it, you would insert the new data only to the copy of the array that was created for your foreach loop.
This works:
foreach ($permissions as &$eachPermission) {
foreach ($eachPermission as &$singlePermission) {
$encodedPermission = base64_encode($singlePermission['permission']);
array_push($singlePermission, "encodedPermission", $encodedPermission);
}
}
var_dump($permissions);
i would do it like this just because it is easier to understand ...
foreach($permissions as $name1=>$ar1){
foreach($ar1 as $name2=>$ar2){
$permissions[$name1][$name2]['encodedPermission'] = base64_encode($ar2['permission']);
}
}
I'm trying to write a function which counts array elements recursively.
But result is false.
What could it be problem?
$schema = array(
'div' => array(
'class' => 'lines',
'div' => array(
'span' => array(
'key' => 'Product Name'
),
'val' => 'Soap'
),
'layer' => array(
'span' => array(
'key' => 'Product Name'
),
'val' => 'Ball'
)
)
);
function count_r($array, $i = 0){
foreach($array as $k){
if(is_array($k)){ $i += count_r($k, count($k)); }
else{ $i++; }
}
return $i;
}
echo count_r($schema);
This is the second result on Google so I'm adding this as a reference. There is already a built-in function in PHP that you can use: count().
You can use it like this:
count($schema, COUNT_RECURSIVE);
This function can also detect recursion to avoid infinite loops so it's safer than solutions in other answers.
PHP has a built-in method for this purpose, called count(). If passed without any additional parameters, count() returns the number of array keys on the first level. But, if you pass a second parameter to the count method count( $schema, true ), then the result will be the total number of keys in the multi-dimensional array. The response marked as correct only iterates first and second level arrays, if you have a third child in that array, it will not return the correct answer.
This could be written as a recursive function, if you really want to write your own count() method, though.
Transferred from comment below answer:
Basically, as you're adding the count_r of that array to the current level, you don't need to factor in the count in the second argument - you'd basically be adding it twice. You need the "1" in there, however, to count the array itself. If you'd want to count just the elements and not the arrays, you would just make the "1" a "0".
$schema = array(
'div' => array(
'class' => 'lines',
'div' => array(
'span' => array(
'key' => 'Product Name'
),
'val' => 'Soap'
),
'layer' => array(
'span' => array(
'key' => 'Product Name'
),
'val' => 'Ball'
)
)
);
function count_r($array, $i = 0){
foreach($array as $k){
if(is_array($k)){ $i += count_r($k, 1); }
else{ $i++; }
}
return $i;
}
echo count_r($schema);
This is tested and works correctly.
your function could be simple as
function count_r($array, $i = 0){
foreach($array as $k){
$i++;
if(is_array($k)){
$i += count_r($k);
}
}
return $i;
}
I have altered you code.. Please check it. It is working fine.
$schema = array(
'div' => array(
'class' => 'lines',
'div' => array(
'span' => array(
'key' => 'Product Name'
),
'val' => 'Soap'
),
'layer' => array(
'span' => array(
'key' => 'Product Name'
),
'val' => 'Ball'
)
)
);
function count_r($array){
foreach($array as $k){
if(is_array($k)){
$i += count_r($k);
}
else{
$i++;
}
}
return $i;
}
echo count_r($schema);
If you want to count specific keys/values you can use the built-in array_walk_recursive with a closure function.
$schema = array(
'div' => array(
'class' => 'lines',
'div' => array(
'span' => array(
'key' => 'Product Name'
),
'val' => 'Soap'
),
'layer' => array(
'span' => array(
'key' => 'Product Name'
),
'val' => 'Ball'
)
)
);
$elements = 0;
array_walk_recursive($schema, function($value, $key) use (&$elements) {
if (strstr($value, 'Product')) $elements++;
});
print $elements; // 2
/*
Values
lines
Product Name
Soap
Product Name
Ball
Keys
class
key
val
key
val
*/
count($array, COUNT_RECURSIVE)-count($array)
I have been looking how to do this and am a bit stumped.
My array is as follows:
$returndata->setup_array = array(
'General' => array(
'Main Details' => 'setup/maindets',
'Directories' => 'directories',
'Extension Allocation' => 'xtnallo',
'List Holidays' => 'setup/holidays',
'List Group VM' => 'groupvm',
'Conference Rooms' => 'confroom'
),
'Offices' => array(
'List Offices' => 'iptoffices'
),
'Users' => array(
'List Users' => 'iptusers'
),
'Phones' => array(
'List Phones' => 'iptphones'
),
);
However I have 1 item that on a certain condition(triggered by the users session) that needs to be added to the listin the general array. The section being 'View Details => setup/viewdetails'. I have tried array push (probably incorrectly) but this adds the item as another array at the end under the main array.
I want/need it to work like this:
$returndata->setup_array = array(
'General' => array(
$viewdets
'Main Details' => 'setup/maindets',
'Directories' => 'directories',
'Extension Allocation' => 'xtnallo',
'List Holidays' => 'setup/holidays',
'List Group VM' => 'groupvm',
'Conference Rooms' => 'confroom'
),
'Offices' => array(
'List Offices' => 'iptoffices'
),
'Users' => array(
'List Users' => 'iptusers'
),
'Phones' => array(
'List Phones' => 'iptphones'
),
);
$viewdets = "'View Details' => 'setup/viewdetails'";
and still be interpreted as a functioning array for use as a menu.
$returndata->setup_array['General']['View Details'] = 'setup/viewdetails'
Cheers Rick!
You can use ArrayObject to have the array as a reference:
$a = new ArrayObject();
$b = array(
"a" => $a
);
$a[] = "foo";
print_r($b);
What did you try calling array_push() on? Have you tried
array_push($returndata->setup_array['General'], $viewdets);
You would need to add the variable to the specific depth of the array you wanted it to be present. check out array_push here, there's also a short language syntax that avoids the function call:
$returndata->setup_array['General'][] = $viewdets;
I have the following two things:
$_POST array with posted data
$params array with a path for each param in the desired data array.
$_POST = array(
'name' => 'Marcus',
'published' => 'Today',
'url' => 'http:://example.com',
'layout' => 'Some info...',
);
$params = array(
'name' => 'Invoice.name',
'published' => 'Page.published',
'url' => 'Page.Data.url',
'layout' => 'Page.Data.layout',
);
I would like to generate the $data array like the example below.
How can I do that?
Notice how the "paths" from the $params array are used to build the keys for the data array, filling it with the data from the $_POST array.
$data = array(
'User' => array(
'name' => 'Marcus',
),
'Page' => array(
'published' => 'Today',
'Data' => array(
'url' => 'http:://example.com',
'layout' => 'Some info...',
),
),
);
I would use referenced variables:
$post = array( // I renamed it
'name' => 'Marcus',
'published' => 'Today',
'url' => 'http:://example.com',
'layout' => 'Some info...',
);
$params = array(
'name' => 'Invoice.name',
'published' => 'Page.published',
'url' => 'Page.Data.url',
'layout' => 'Page.Data.layout',
);
echo '<pre>'; // just for var_dump()
foreach($post as $key=>$var){ // take each $_POST variable
$param=$params[$key]; // take the scheme fields
$path=explode('.',$param); // take scheme fields as an array
$temp=array(); // temporary array to manipulate
$temp_original=&$temp; // we need this the same as we're going to "forget" temp
foreach($path as $pathvar){ // take each scheme fields
$temp=&$temp[$pathvar]; // go deeper
}
$temp=$var; // that was the last one, insert it
var_dump($temp_original); // analize carefully the output
}
All you have to do now is to combine them all, they are not exactly what you want, but this will be easy.
And please note, that each $temp_original fields are pointing at $post variable data! (&string instead of string). You may want to clone it somehow.