how to print 2d array in laravel 5.4.12 by dd();? - laravel

please help me to solve this problem that how to die and dump 2D array in laravel and count array in an array.. i tried this but not working
$arr=collect($request->input('title['+$i+']'));
dd($arr->count());
also tried this code
$arr=collect($request->input('title[0]'));
dd($arr->count());

You do not say that you need to count them in your questions but here you go:
The aray:
$arrayname= array(
array('a', 'b', 'c'),
array('r', 't','y', 'u'),
);
The function
for ($i=0; $i < count($arrayname); $i++){
$singlearray[$i]= count($arrayname[$i]);
}
Result
array:2 [▼
0 => 3
1 => 4
]

dd($request->all()) will display contents of the array.
If you want to see the title, do this:
dd($request->title);

try to use:
echo count($arr);
dd($arr);
or
echo count($arr);
print_r($arr);
die;

$a = $request->all();
$flatArray = [];
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach($it as $v) {
$array[] = $v;
}
dd(count($flatArray));
Resource:
How to Flatten a Multidimensional Array?

i get it from the other site... Answer here
dd(count(request('title')[0]));
dd(count(request('title')['age']));

Related

Count number of same values in JSON array and convert it to string

My JSON looks something like this:
[
{"pet_type":"Dog","weight":"26","description":"Akita"},
{"pet_type":"Dog","weight":"6","description":"Pug"},
{"pet_type":"Cat","weight":"4","description":"Manx"},
{"pet_type":"Dog","weight":"12","description":"Beagle"},
{"pet_type":"Cat","weight":"5","description":"Siberian"}
]
How could I convert it to a string which would look like3 Dogs, 2 Cats?
The way I tried is filling an array with pet_type and than use array_count_values to count number of same records, and later I go through that array in a foreach and concat string like this:
foreach ($count_animals as $type => $number) {
$animals .= $number.' '.str_plural($type, $number).', ';
}
This works, but my question is, could I do it with less code, directly from JSON, without using one more foreach loop?
If it works, you can keep your code.
If you want less code, you can use this version :
$json = '[
{"pet_type":"Dog","weight":"26","description":"Akita"},
{"pet_type":"Dog","weight":"6","description":"Pug"},
{"pet_type":"Cat","weight":"4","description":"Manx"},
{"pet_type":"Dog","weight":"12","description":"Beagle"},
{"pet_type":"Cat","weight":"5","description":"Siberian"}
]';
print_r(array_count_values(array_map(function($item) {
return $item['pet_type'];
}, json_decode($json, true))));
Gonna display :
Array ( [Dog] => 3 [Cat] => 2 )
in your controller
$pet = Pet::get();
$petcount = Pet::where('pet_type','Dog')->get();
In your blade
<h1>{{count($petcount)}} Dog</h1>

How I can get 0 index value in codeigniter?

Array ( [0] => 18 [1] => 1 )
how i can get only 0 index value?. I am using this code in codeigniter. Can any one help?. Is this possible with for each loop so it access all indexes but show only zero index?
foreach($m as $m)
{
echo $m->['0'];
}
If you want only first index then you don't need to foreach loop
Just write:
echo $m[0];
And if you want all index of array then:
foreach ($m as $key => $value) {
echo $key;
}
Try this:
print_r($m[0]);
or
foreach($m as $m)
{
echo $m['0'];
}
Following is the code to get value of index 0
//$array variable declared containing multiple values
$array=array('0' =>"first value",'1' =>"second value",'2' =>"third value" );
echo "<pre>";
print_r($array); // helps in printing the value key and value
//iterating through each values in the array
foreach ($array as $key => $value) {
if($key==0) //checks if key is 0
{
echo $value; //prints the value in key 0
}
}

Cakephp 3 How to make session array

I am trying to write session in controller. My structure is
$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;
And I am trying this
Configure::write('Session', ['a' =>'1'])
But it is not working. How do this in cakephp 3 way
To write variable in Session in CakePHP 3 you need to write following code :
$this->request->session()->write('Your Key',Your_array);
To know more information you can visit here :
http://book.cakephp.org/3.0/en/development/sessions.html
To make things perfectly clear:
// code writing array to session
$a = [ "abc" => "word", "123" => 42, "?" => $b ];
$a["more"] = "if you need to add";
$a[] = "whatever";
$this->request->session()->write( 'my_array', $a );
// code reading array from session
$recall = $this->request->session()->read( 'my_array' );
debug( sprintf( "What's the word? [%s]", $recall["abc"] ) );
You can simply use
$session->write([
'key1' => 'blue',
'key2' => 'green',
]);
I am refering to
http://book.cakephp.org/3.0/en/development/sessions.html#reading-writing-session-data
The answer is that this cannot be done in CakePHP 3.x
In vanilla PHP, it's possible to do this:
<?php
session_start();
$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;
var_dump($_SESSION);
?>
Which will output:
array(1) {
["a"]=> array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
}
}
This is correct, and what should happen.
In CakePHP, you cannot specify arrays in the session key. For example:
$this->request->session()->write('a[]', 1);
$this->request->session()->write('a[]', 2);
$this->request->session()->write('a[]', 3);
Will not work.
If you remove the [] the value will get overwritten. For example:
$this->request->session()->write('a', 1);
$this->request->session()->write('a', 2);
$this->request->session()->write('a', 3);
The value of $this->request->session()->read('a') would be 3. The values 1 and 2 have been overwritten. Again, this is to be expected because you're overwriting the key a each time. The equivalent vanilla PHP for this is:
$_SESSION['a'] = 1;
$_SESSION['a'] = 2;
$_SESSION['a'] = 3;
Due to the lack of an indexed array, $_SESSION['a'] gets overwritten each time. This is normal behaviour. It needs to have the indexes (e.g. ['a'][0], ['a'][1], ...) to work!
The other answers where they have given things like key1 and key2 are not appropriate. Because there are many situations where you want everything contained within an indexed array. Generating separate key names is wrong for this type of scenario.
My edit of the accepted answer was rejected, so I present the - seemingly necessary - explicit code example, for the benefit of #Andy and others.
// code to write to session
$a = [ 0 => "zero", 1 => "one", 2 => "two" ];
$a[] = "three";
$this->request->session()->write( 'my_array', $a );
// code to read from session
$z = $this->request->session()->read( 'my_array' );
debug( $a[3] ); // outputs "three"

Symfony findOneBy / findBy

Has anyone face this strange issue with Symfony 3 (very last version)?
I have the following simple code:
$repository = $this->getDoctrine()
->getManager()
->getRepository('GeneralRegistrationBundle:Service');
$service = $repository->findOneBy(array('name' => 'Registration'),array('name' => 'ASC'));
$comment = $service->getComment();
$name = $service->getName();
return new Response('le service is '. $name . ', content is ' . $comment);
this code works.
I purge the cache and change findOneBy with findBy:
$service = $repository->findBy(array('name' => 'Registration'),array('name' => 'ASC'),1 ,0);
then I have the following error:
Error: Call to a member function getComment() on array
Is anybody have ideas or clues?
Thanks in advance.
findBy() returns an array of objects with the given conditions.
It returns an empty array if none is found. If there is only one row satisfying your condition then you can add a [0] at the last of your $service like this:
$service = $repository->findBy(array('name' => 'Registration'),array('name' => 'ASC'),1 ,0)[0];
if not, you should loop through the found array with foreach or some thing similar.
If you want and expect one result you can use findOneBy() function.
$service = $repository->findOneBy(array('name' => 'Registration'),array('name' => 'ASC'),1 ,0)[0];

Laravel Eloquent: getDictionary with object value as value of result

Currently, $mymodel->getDictionary(); returns:
What I am looking for is this:
"7gct5YaTvuxBmY2" => "Leadership",
"7NrXZepqczMSHqM" => "...",
"..." => "...",
...
The only way I have managed to do this is:
$construct_obj = OrganizationalConstruct::where('is_root', 0)->where('organization_id', $this->current_company->company_id)->get();
$constructs = [];
$constructs[''] = '';
for ($i = 0; $i < count($construct_obj); $i++) {
$constructs[$construct_obj[$i]->organizational_construct_id] = $construct_obj[$i]->construct_name;
}
Is there an easier way of getting the format "key" => "speific-column-value" ?
I have tried:
keyBy
lists
getDictionary
map
You should call pluck directly on the query, so that you don't pull down all attributes for all models:
$dictionary = OrganizationalConstruct::where('is_root', 0)
->where('organization_id', $this->current_company->company_id)
->pluck('construct_name', 'organizational_construct_id');
Note: lists is deprecated, and will be removed in Laravel 5.3. Use the pluck method instead.
Quite a simple answer actually. It looks like the lists methods can accept more than 1 argument, allowing me to pass through the id as parameter 1 and name as parameter 2 giving me the required result of key => value in one line.
So this:
$construct_obj = OrganizationalConstruct::where('is_root', 0)->where('organization_id', $this->current_company->company_id)->get();
$constructs = [];
$constructs[''] = '';
for ($i = 0; $i < count($construct_obj); $i++) {
$constructs[$construct_obj[$i]->organizational_construct_id] = $construct_obj[$i]->construct_name;
}
becomes this:
$construct_obj = OrganizationalConstruct::where('is_root', 0)->where('organization_id', $this->current_company->company_id)->get();
$construct_obj->lists('construct_name', 'organizational_construct_id');
Hope this helps someone else.

Resources