Here is what I put in my Symfony session
$this->session->set('teams', [
'team_1' => ['MyTeamNameA' => ['player-1' => $safe['team-1-player-1'], 'player-2' => $safe['team-1-player-2'], 'player-3' => $safe['team-1-player-3'], 'player-4' => $safe['team-1-player-4'], 'points' => 0]],
'team_2' => ['MyTeamNameB' => ['player-1' => $safe['team-2-player-1'], 'player-2' => $safe['team-2-player-2'], 'player-3' => $safe['team-2-player-3'], 'player-4' => $safe['team-2-player-4'], 'points' => 0]],
]);
And now, in my Twig, I want to retrieve my team_1's name, for example, I did this:
app.session.get('teams')['team_1']
It doesn't work, but, if I do a dump of this last piece of code, I get this result pictured below:
I feel that i'm close to the answer, and yet so far.
Since keys will return you a simple array, then the keys are integer from 0 to the (array | length) - 1, to express it in Twig.
Note that this is actually the same behaviour as PHP, when you define an array like
['foo', 'bar', 'baz']
that would be strictly equivalent to
[0 => 'foo', 1 => 'bar', 2 => 'baz']
So in your case, since you only have one element in the array you can use array[0] or array.0.
All together, this would work:
{{ (app.session.get('teams').team_1 | keys).0 }}
Could be tested from https://twigfiddle.com/b6iy8i
Related
This is my collection data
[
0 => object(App\Model\Entity\SummaryCoin) id:0 { 'user_id' => (int) 2
'total_sum_coin' => (float) 3 },
1 => object(App\Model\Entity\SummaryCoin) id:1 { 'user_id' => (int) 1
'total_sum_coin' => (float) 33 },
]
How can I get the index where user_id = 1
Using first match I am able to get user 1 new collection
$sumOfUserCoins = $collection->firstMatch([
'user_id' => 1
]);
How I will get the array index 1 that user have ?
There is no specific method for that, you'll have to be a little creative to obtain that information, for example match all instead so that you get a collection back, take everything away expect for the first entry, and convert it to an array that keeps the keys, from which you can then get that information:
$userCoins = $collection
->match(['user_id' => 1])
->take(1)
->toArray();
$index = key($userCoins);
$coin = current($userCoins);
from request I get an array like this:
'array' => [
0 => ['id' => 1,'val' => 2],
1 => ['id' => 1,'val' => 2]
]
I need to validate it so all ids of array will be unique.
right now I try this validation rule:
'array.*.id' => 'different:array.*.id'
but it will check current array with current array so result will be like
The array.0.id and array.0.id must be different.
You should use distinct rule:
'array.*.id' => 'distinct'
When you retrieve records using $this->paginate('Modelname') with some page limit, how do you get the total number of records retrieved?
I'd like to display this total count on the view, but count($recordsRetrieved) returns the number displayed only on the current page. So, if total number of records retrieved is 99 and limit is set to 10, it returns 10, not the 99.
You can debug($this->Paginator->params());
This will give you
/*
Array
(
[page] => 2
[current] => 2
[count] => 43
[prevPage] => 1
[nextPage] => 3
[pageCount] => 3
[order] =>
[limit] => 20
[options] => Array
(
[page] => 2
[conditions] => Array
(
)
)
[paramType] => named
)
*/
The final code for PHP >=5.4:
$this->Paginator->params()['count'];
For PHP versions less than 5.4:
$paginatorInformation = $this->Paginator->params();
$totalPageCount = $paginatorInformation['count'];
To get your answer go to he following link
http://book.cakephp.org/2.0/en/controllers/request-response.html
use pr($this->request->params) you will find all the stuff of pagination
For cake 3.x
you can use method getPagingParams
example:
debug($this->Paginator->getPagingParams());
output:
[
'users' => [
'finder' => 'all',
'page' => (int) 1,
'current' => (int) 5,
'count' => (int) 5,
'perPage' => (int) 1,
'prevPage' => false,
'nextPage' => true,
'pageCount' => (int) 5,
'sort' => null,
'direction' => false,
'limit' => null,
'sortDefault' => false,
'directionDefault' => false,
'scope' => null
]
]
Here's how I got the count from my controller*
This is for CakePHP 2.3. It uses a view helper, which is typically a no-no in the controller as it violates MVC, but in this case I think makes sense to keep the code DRY.
// Top of file
App::uses('PaginatorHelper', 'View/Helper');
// Later in controller method
$paginatorHelper = new PaginatorHelper(new View(null));
$records = $this->paginate();
$count = $paginatorHelper->params()['count'];
* I know the OP asked about from the view, but I figure if Arzon Barua's answer is helping people (though I think it only tells you the requested count, not the actual count as the OP wants), then this might help too.
This way is getting a pagination information over controller.
class YourController extends Controller{
$helpers = array('Paginator');
public fn(){
$view = new View(null);
var_dump($view->paginator->params());
}
}
I'm working on a script and trying to get some values from an array stored in a hash. After searching on Google, searching for questions on SO (and there are some with similar titles but which have remained unsolved or solve problems a little bit different than mine), and after checking out the Data Structures Cookbook and trying everything reasonable to try, I've come to ask your help.
I have a hash, $action, and an array, $action->{'Events'}. Here's the output for print Dumper($action->{'Events'});:
$VAR1 = [{
'Muted' => 'something',
'Role' => 'something',
'Event' => 'something',
'Channel' => 'something',
'Talking' => 'something',
'UserNumber' => 'somenumber',
'CallerIDName' => 'somenumber',
'Conference' => 'somenumber',
'MarkedUser' => 'something',
'ActionID' => 'somenumber',
'CallerIDNum' => 'somenumber',
'Admin' => 'something'
}];
I need to get, for example, the value of $action->{'EVENTS'}->{'CallerIDName'}, but this syntax and many other won't work. I've even tried $action->{'EVENTS'}[6] and $action->{'EVENTS'}->[6] and so on.
It is Array of hashes, try this way:
$action->{'EVENTS'}[0]->{'CallerIDName'}
see perldsc for more detail.
Updated example like:
use strict;
use warnings;
use Data::Dumper;
my $action = {};
$action->{'Events'} = [{'Muted' => 'something',
'Role' => 'something',
'Event' => 'something',
'Channel' => 'something',
'Talking' => 'something',
'UserNumber' => 'somenumber',
'CallerIDName' => 'somenumber',
'Conference' => 'somenumber',
'MarkedUser' => 'something',
'ActionID' => 'somenumber',
'CallerIDNum' => 'somenumber',
'Admin' => 'something'}];
#push hash into the array of hashes
push(#{$action->{'Events'}},{'Muted' => 'something',
'Role' => 'something1',
'Event' => 'something1',
'Channel' => 'something1',
'Talking' => 'something1',
'UserNumber' => 'somenumber1',
'CallerIDName' => 'somenumber1',
'Conference' => 'somenumber1',
'MarkedUser' => 'something1',
'ActionID' => 'somenumber1',
'CallerIDNum' => 'somenumber1',
'Admin' => 'something1'} );
for(my $i=0; $i < #{$action->{'Events'}}; $i++){
print Dumper($action->{Events}[$i]); #print entire hash in array index $i
#print callerIDName key(any key) of each hash
print Dumper($action->{'Events'}[$i]->{'CallerIDName'});
}
The one you're missing is that the $action contains a reference to an array, so the next part must dereference the array. Then within that is a hash, and you need to dereference the hash. So it should look like this:
$action->{'EVENTS'}[0]{'CallerIDname'}
(note that the ->'s beyond the first are optional, so this is fine as well:
$action->{'EVENTS'}->[0]->{'CallerIDname'}
And does the exact same thing)
The [ ] on the outside indicate the hash is inside an array. So try:
$action->{Events}->[0]->{CallerIDName}
You can omit the -> between the {Events} and [0], but I prefer it for clarity. It doesn't make a difference here, but it does in other places. Compare:
#array = (1,2,3);
$arrayref = \#array;
print $arrayref[0]; # accesses non-existent array #arrayref
print $arrayref->[0]; # '1'
In CakePHP, it seems like a lot of functions can take their arguments as nested, multidimensional arrays, or as dotted strings:
$this->MyModel->contain(array(
'Something', 'Something.Else', 'Something.Else.Entirely'
));
$this->MyModel->contain(array(
'Something' => array(
'Else' => 'Entirely'
)
));
Therefore, I figure there must be a function somewhere in the core to switch from dotted to nested associative, but I can't find it for the life of me. Any ideas?
I've actually figured my own way to get this working leveraging the built-in Set functions.
Given:
$input = array (
'Post.id' => 1,
'Post.title' => 'Some post title.',
'Post.Tag.0.id' => 4,
'Post.Tag.0.name' => 'cakephp',
'Post.Tag.1.id' => 7,
'Post.Tag.1.name' => 'mysql',
);
This code will put that into a nested associative array.
$output = array();
foreach ($input as $key => $value) {
$output = Set::insert($output, $key, $value);
}
Here's the docs for Set::insert()
What you're looking for is Set::flatten(). It's not documented in the CakePHP manual, but take a look at the API definition.
It works something like this (the result might not be exact, this is from my head):
$array = array(
'Post' => array(
'id' => 1,
'title' => 'Some post title.',
'Tag' => array(
0 => array(
'id' => 4,
'name' => 'cakephp',
),
1 => array(
'id' => 7,
'name' => 'mysql',
),
),
);
);
$array = Set::flatten($array);
var_dump($array);
Your $array variable will now look like this:
Array (
'Post.id' => 1,
'Post.title' => 'Some post title.',
'Post.Tag.0.id' => 4,
'Post.Tag.0.name' => 'cakephp',
'Post.Tag.1.id' => 7,
'Post.Tag.1.name' => 'mysql',
)
It's just a convention throughout Cake, but each part does its own, customized parsing. If you look at the function ContainableBehavior::containments() in cake/libs/model/behaviors/containable.php, you'll see a lot of preg_matching and explode('.')ing going on. At least in the case of Containable, the verbose array('name' => array(...)) syntax seems to be the canonical syntax, but it can be abbreviated with the dot syntax, which will just be expanded. I'd guess that the expanding itself is just too varied among different parts to be easily summarized in a central function.
That, or they just haven't gotten to it yet. :)
Great question, I was just searching for the same thing. Apparently it's coming in Cake 2.2.
The new Hash class (a new, improved version of the Set class) has an expand() function which does this. You can view the code on Github if you need to use it in the meantime:
https://github.com/cakephp/cakephp/blob/2.2/lib/Cake/Utility/Hash.php
...However the solution nickf posted works great, too. :-)