Laravel request is an array but not recognized by count() - php

I am passing an array into my controller via axios.post request. I am trying to get the length of the $request array that I am passing to the controller. However, I keep recieving a "Parameter must be an array or an object that implements Countable" error.
Here is what my array looks like:
array (
0 =>
array (
'text' => 'It is this',
'question_id' => 98,
),
1 =>
array (
'text' => 'And it is that',
'question_id' => 98,
),
2 =>
array (
'text' => 'Also a little bit of this',
'question_id' => 98,
),
Here is what I have tried:
$count = sizeof($request));
$count = $request->length;
$count = count($request);
The only thing that has had even a little bit of success is doing:
$count = count($request[0])
This returns 2, which is for the elements inside the first array. It counts text, and question_id. While this is good progress this is not what I want
What I would like to see happen is to have the length of the entire $request object. In the example I gave above, I would like to either receive 2, (the end of 0,1,2) or 3 (the count of 0,1,2).

If $request is an Illuminate\Http\Request, it won't be directly countable.
You can count $request->all() or $request->input(), though.

What about:
count($request->all());

In as much as the accepted answer will count the number of items in the requests, it will not count the number of items in a single request request item say C. If you are sure that C is an array and C is part of the request then doing count($request->C) not e that count here is a regular PHP function

try ;
count($request->all());

Related

Yii 2.0 $request->post() issues

In my controller I have the following lines
$request = Yii::$app->request;
print_r($request->post());
echo "version_no is ".$request->post('version_no',-1);
The output is given below
Array
(
[_csrf] => WnB6REZ6cTAQHD0gAkoQaSsXVxB1Kh5CbAYPDS0wOGodSRANKBImVw==
[CreateCourseModel] => Array
(
[course_name] => test
[course_description] => kjhjk
[course_featured_image] =>
[course_type] => 1
[course_price] => 100
[is_version] => 1
[parent_course] => test
[version_no] => 1
[parent_course_id] => 3
[course_tags] => sdsdf
)
)
version_no is -1
So here the return value of post() contains the version_no.But when it is called as $request->post("version_no"), it is not returning anything (or $request->post("version_no",-1) returns the default value -1).
As per Yii 2.0 docs, the syntax is correct and should return the value of post parameter.
But why is it failing in my case.The post array has the parameter in it.But the function is not returning when called for an individual parameter value.
your parameters are in $_POST['CreateCourseModel']['version_no'] etc. with $request->post('version_no',-1) you trying to get $_POST['version_no'] which is not defined so it returns you -1. So to get version_no use
$data = $request->post('CreateCourseModel');
print_r($data['version_no']);
You can access nested $_POST array elements using dot notation:
\Yii::$app->request->post('CreateCourseModel.version_no', -1);
Model properties are grouped like that for massive assignment that is done via $model->load(Yii::$app->request->post()).
Depending on your needs maybe it's better use default value validator like that:
['version_no', 'default', 'value' => -1],

Force json_encode to return array instead objects

I've been wondering if it's possible to force json_encode into returning Array instead an Object while still keeping the "integer" index.
What am I trying to achieve if you're asking is an array of usernames ( with their userID's as keys in the array ).
So if I have a list of mutual friends like this in PHP:
1 => 'John Doe',
2 => 'Jane Doe',
5 => 'Oliver Natefield',
11 => 'Chris Cole'
I'd like to use json_encode and I tried two methods.
First one is by simply adding into an empty PHP Array, values to their respective index ( userID ).
<?php
$list = array( );
foreach ( $friends as $userID => $name )
$list[ $userID ] = $name;
echo json_encode( $list );
?>
That creates me an Object sadly. Ok, then I tried something else...
<?php
$list = array( );
foreach ( $users as $userID => $name )
array_splice( $list, $userID, 0, $name );
echo json_encode( $list );
?>
Again, failed, this time, it's an Array, but the indexes are not taken into consideration.
I know that.. the array should be like :
undefined, // userID 0
'John Doe', // userID 1
'Jane Doe', // userID 2
undefined, // userID 3
undefined, // userID 4
'Oliver Natefield', // userID 5
undefined, //userID 6
undefined, // etc
But... if I have a friend with userID with the index 1504 .. shouldn't there be a memory downside ?
And while we're at it, can I see how much memory does an array of 1000 undefined elements use ? It's relevant because if it consumes too much memory, I'll just have to search through an array of objects for a username after a specific userID.
This is not really possible. It's a restriction of Javascript syntax, which is basically what JSON is. You can't specify array keys in a Javascript "shortcut" array definition, like you can with PHP. e.g.
$foo = array(1 => 'a', 10 => 'b');
There's no such notation in JS, the only shortcut allowed is
foo = ['a', 'b'];
which would give you the PHP equivalent 0 => 'a', 1 => 'b'. To use non-sequential array keys, you MUST use an Object:
foo = {1: 'a', 10: 'b'};

POSTing a multidimensional array from Python

I'm trying to POST an array to a RESTful PHP API. The idea is to allow (n>0) records, each containing a remote_id, a dimension_id and a metric.
Here's my client Python:
data = urllib.urlencode([
("remote_id", 1),
("dimension_id", 1),
("metric",metric1),
("remote_id", 1),
("dimension_id", 2),
("metric",metric2)
])
response = urllib2.urlopen(url=url, data=data)
And here's my serverside PHP
<?php
print_r($_POST);
?>
This returns, predictably:
Array
(
[remote_id] => 1
[dimension_id] => 2
[metric] => 16
)
It looks to me like I'm overwriting every instance of remote_id, dimension_id and metric with the final values, which is unsurprising since they're all keyed with identical names.
What's the proper way to do this? I can see a horrible method with unique keys (1_remote_id, 1_dimension_id, 1_metric + 2_remote_id, 2_dimension_id, 2_metric) but that doesn't scale very well.
I guess I'm after something like this PHP, but in Python:
<?php
$observations = array();
$observations[] = [
"remote_id" => "a1",
"metric_id" => "foo",
"metric" => 1
];
$observations[] = [
"remote_id" => "a1",
"metric_id" => "bar",
"metric" => 2
];
?>
Appreciate any tips!
Sam
Don't quote me on this (I haven't done any PHP in a LOOONG time), but this may just work:
data = urllib.urlencode([
("remote_id[]", 1),
("dimension_id[]", 1),
("metric[]",metric1),
("remote_id[]", 1),
("dimension_id[]", 2),
("metric[]",metric2)
])
I would give it a try anyway.

Mongodb php compound query returns nothing

I have the following array:
Array
(
[data.cars] => 44
[data.xp] => Array
(
[$gte] => 100
[$lte] => 500
)
[data.money] => Array
(
[$gte] => 200
[$lte] => 1000
)
)
When issuing this array to find it returns NULL.
Am I doing something wrong, I formated it according to this page, here:
http://us1.php.net/manual/en/mongo.sqltomongo.php
So basically, if I have
SELECT * FROM mytable WHERE data.cars = 44 AND data.xp >= 100 AND data.xp <= 500 AND data.money >= 200 AND data.money <= 1000
This query when run in the console gives exactly 4 results.
Here is the query:
{$and:[{"data.cars":44}, {"data.xp": {$gt:100, $lt:500}}, {"data.money": {$gt:200, $lt:1000}}]}
My array should work, but hey, it does not, please point me to what I'm doing wrong.
Thank you!
The query on MongoDB PHP should be formatted like this:
array(
'data.cars' => 44,
'data.xp' => array(
'$gt' => 100,
'$lt' => 500
),
'data.money' => array(
'$gt' => 200,
'$lt' => 1000
)
)
By doing json_encode() on two version of arrays, both at first sight seem identical, but as you will see, they are not, I discovered the "bug".
Both array's look like so:
array(
'data.cars' => 44,
'data.xp' => array(
'$gt' => 100,
'$lt' => 500
),
'data.money' => array(
'$gt' => 200,
'$lt' => 1000
)
);
One was hardcoded the other was dynamically built, but both json encoded were different, here they are:
{"data.cars":"44","data.xp":{"$gte":"100","$lte":"500"},"data.money":{"$gte":"200","$lte":"1000"}}
{"data.cars":44,"data.xp":{"$gte":100,"$lte":500},"data.money":{"$gte":200,"$lte":1000}}
The first array had the values as string, but couldn't see that on a regular print_r or a var_dump, so what I did was a force cast on the values and ... it WORKED :)
Thank you all guys for your effort and interest!
First of all it is really bad to use . or $ symbols in a keys name (and I actually thought that this is illegal ). This is because dot operator is used to access subdocuments.
So the first thing is to change that. The second thing is that you do not need $and there. So if you want to find the document, which has a = 1 and b = 2, then you do not need to do {$and : .... } all you need to do is {a : 1, b : 2}

Efficient array value replacement

I have an array of values in PHP looking something like this:
$test = array (
array( 'val' => 2, 'color' => 'blue' ),
array( 'val' => 5, 'color' => 'green' ),
);
I want to go through all elements of $test and add 1 to all val indices. Now I realize a foreach loop could work, but I am looking for something a little more efficient. The array will potentially have 10's of thousands of elements and hundreds of sub-elements.
I am wondering if there is some type of way that PHP can go through and modify just that index throughout the entire array, based on the argument that I set.
you can use array_walk and a closure to do it
array_walk($yourArray,function(&$col){$col['val']++});

Categories