I upload several files with Zend and want to count the $data array to get the filenames.
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
I found this code for counting in another post
array_sum(array_map("count", $data))-1;
It gives the right amount of pieces and I can get the names, but it also gives a warning:
Warning: count(): Parameter must be an array or an object that
implements Countable
I tried to give the other dimensions like:
array_sum(array_map("count", $data['fieldname']))-1;
But like expected, it doesn't work.
Any help appreciated! The only question is how to get the amount of given filenames.
***edit regarding to the answer I post a screenshot how the $data array looks like, which is correct
And here what the statement with the warning counts (of course 1 is to subtract). Perhaps there is an other possibility to count.
So everything might be nice, but I want to get rid of the warning.
Judging by the added screenshot of the $data array, shouldn't you be doing this the below?
count($data['PAD_Document_Path'])
Get specific filenames by looping like so
foreach($data['PAD_Document_Path'] as $key => $value) {
$name = pathinfo($value)['filename'];
// do stuff with name
}
See pathinfo. From that docs page:
Example #1 pathinfo() Example
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>
The above example will output:
/www/htdocs/inc
lib.inc.php
php
lib.inc
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 1 year ago.
Here's the json
{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}
Here's my code
$json = json_decode($data);
foreach($json["result"] as $result){
foreach($result["files"] as $file){
echo $file["file_code"];
}
}
I want to extract all values from the "file_code". I got an error
Warning: Invalid argument supplied for foreach()
I was able get the VALUE of the first one using
echo $json->result->files[0]->file_code;
Is it possible to use a LOOP for the files[0]?
This line:
foreach($json["result"] as $result){
sees $json['result'] as an object, and so the next line tests for total_pages["files"], which doesn't exist.
Putting both foreach's together solves the problem:
$data='{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}';
$json = json_decode($data, true);
foreach($json["result"]["files"] as $file)
print $file["file_code"];
Teh playground
Alternatively, make the JSON result into an array, and use object property accessors instead of associative array bindings.
$data='{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":[{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}]}';
$json = json_decode($data);
foreach($json->result as $result){
foreach($result->files as $file){
echo $file->file_code;
}
}
Teh playground
I replicated your situation and it turns out that your JSON is invalid. You're missing a } at the end.
The reason for not getting an exception is because json_decode does not throw an error by default. You can make it do so by adding the JSON_THROW_ON_ERROR flag,
read the docs for more info.
This works perfect for me. If you have any thoughts please feel free to correct me.
$num = count($json->result->files);
echo $num;
for($i=0;$i<$num;$i++)
{
echo $json->result->files[$i]->file_code;
}
I'm having some problems getting the data through my PHP loop.
<?php
$url = 'https://www.fibalivestats.com/data/1653309/data.json';
$content = file_get_contents($url);
$json = json_decode($content, true);
?>
<?php
foreach($json['totallds']['sPoints'] as $item); {
echo $item;
}
?>
The error I'm getting is an array to string conversion error. What I'm trying to get is the data from the sPoints array that will give me a Top 5 points scorers for a basketball game.
I'll build a table for this in HTML later but for now, it's not displaying the data at all and I'm getting errors. I feel like I may have confused arrays and strings too. Any thoughts about what I'm doing wrong? JSON file can be found in the $url variable.
Also if it helps, here's the link to where I have gotten the data from and what context the Top 5 is from https://www.fibalivestats.com/u/NSS/1653309/lds.html
Thanks!
Your $item is an array, so you can't just echo it like that. You can, however, echo its columns, for example:
foreach($json['totallds']['sPoints'] as $item) {
echo $item['firstName'] . ' ' . $item['familyName'];
}
Notice the removed semicolon between the foreach () and {.
Well, array to string conversion error means you're trying to echo an array.
If you see the return of the url you are looking at, you can verify that the "sPoints" key returns an array with several objects.
Try to change echo to print_r or var_dump to view entire data or complete your business logic.
Try changing:
echo $item;
to:
var_dump($item);
$str = file_get_contents('http://uapi.alidays.it/service/2.0.0/rs/alidays/applications/fluidtravel/public/baskets/5660609ee4b0ab55863d6c42/contents/selected');
$json =json_decode($str,true);
echo '<pre>' . print_r($json,true) . '</pre>';
foreach($json['data'] as $item['value']['baskettile']) {
echo $item['value']['baskettile']['type'];
echo '<br>';
}
i tried to access the data like this but it says Warning: Invalid argument supplied for foreach()
The value of baskettile is an object with properties like type and status.
It is not an array. It doesn't make sense to iterate over it with foreach(... in ...).
Just access the values directly.
$json['data']['0']['value']['baskettile']['type']
You need to debug your code. Chances are $item is not what you think it is.
The quickest way is to do a var_dump($item) in your foreach. From there you will see that the variable either is not an array or the key does not exist.
So I have run into this problem many times before, but I would always get around it using base64_encode/decode and that would get it working right away.
However, in this application I cannot use that, because I need to be able to query this field and I wouldn't know how I could do that if it was encoded.
Pardon my ignorance, but is there a way to unserialize a multi-dimensional array without using base64 encoding?
Update 1
Removing the strings and turning them to integers fixes the problem. So it is either a problem with strings, or I suspect the " is causing issues. Anyway to work around that?
For this application, the second element of the array represents a date in a format that it would be searched under. Ideally, I would like to leave that as is, but if it is necessary I suppose I can use an integer to represent the number of days away from a constant, and then interpret that result.
Below is the code:
// Load Contact from Database
$returnFields = array('_AttendanceRecords');
$Contact = $app->loadCon(39732,$returnFields);
echo "<pre>";
print_r($Contact);
echo "</pre>";
echo $Contact['_AttendanceRecords'] . "</br>";
// To unserialize...
$AttendanceRecordsLoad = unserialize($Contact['_AttendanceRecords']);
echo "<pre>";
print_r($AttendanceRecordsLoad);
echo "</pre>";
Output is:
Array (
[_AttendanceRecords] => a:1:{i:0;a:3:{i:0;i:1;i:1;s:10:"10-09-2015";i:2;s:1:"1";}} )
a:1:{i:0;a:3:{i:0;i:1;i:1;s:10:"10-09-2015";i:2;s:1:"1";}}
As you can see, the final print_r comes out empty, which I believe is returning false for whatever reason.
Update 2
So after more fiddling around, I made this new code:
Code
$ContactId = 39732;
$returnFields = array('_AttendanceRecords');
$Contact = $app->loadCon($ContactId,$returnFields);
echo $Contact['_AttendanceRecords'] . " - IS result </br>";
echo $str = 'a:1:{i:0;a:3:{i:0;i:0;i:1;s:8:"10-10-15";i:2;i:1;}}'; echo " - str result </br>";
// To unserialize...
$AttendanceRecordsLoad = unserialize($Contact['_AttendanceRecords']);
$AttendanceRecordsLoad1 = unserialize($str);
echo "IS<pre>";
print_r($AttendanceRecordsLoad);
echo "</pre>";
echo "str<pre>";
print_r($AttendanceRecordsLoad1);
echo "</pre>";
Output
a:1:{i:0;a:3:{i:0;i:0;i:1;s:8:"10-10-15";i:2;i:1;}} - IS result
a:1:{i:0;a:3:{i:0;i:0;i:1;s:8:"10-10-15";i:2;i:1;}} - str result
IS
str
Array (
[0] => Array
(
[0] => 0
[1] => 10-10-15
[2] => 1
)
)
I don't understand. The strings appear identical. Yet the result that comes from the database won't unserialize if it contains a string.
Does that make sense to anyone?
Update 3
Ok, so now I used var_dump instead of echo and I get this outputted:
Output
string(61) "a:1:{i:0;a:3:{i:0;i:0;i:1;s:8:"10-10-15";i:2;i:1;}}" - IS
result
string(51) "a:1:{i:0;a:3:{i:0;i:0;i:1;s:8:"10-10-15";i:2;i:1;}}" - str result
So obviously they are not identical. But I tried trim before, and now, and it doesn't remove any hidden extra characters that somehow have lodged themselves in to this string.
What does that mean and how do I correct this?
Ok figured it out by looking at this question:
SOLUTION FOUND - Same strings, but var_dump() says one is 5 characters longer
The fix was using this on the returned result from the database:
html_entity_decode($string], ENT_QUOTES)
Hope that helps someone else too.
Can someone tell me how I can loop through the below array?
http://pastebin.com/rhaF5Zdi
I've tried with out luck:
$_data = json_decode($_data);
foreach ( $_data as $tweet )
{
echo "{$tweet->text}\n";
}
thanks
ps: im follwoing this php script.
http://mikepultz.com/2013/06/mining-twitter-api-v1-1-streams-from-php-with-oauth/
hers another paste bin on the array. there seems to be multiple arrays happening
http://pastebin.com/dduzhpqY
It looks like you might be creating a PHP stnd object instead of an array
//this will create a php standard object
$objOfData=json_decode($json);
Instead Use the version below: (Notice the the 2nd parameter is TRUE)
$associativeArray=json_decode($json, TRUE);
This will turn the object into an associative array and you can access fields like so:
$id=$associativeArray['id'];
More info here: json_decode
The code in posted link is not JSON, but it is output of print_r() function. PHP has no invert function to print_r(), but on php.net in print_r() documentation's comments you can find some user-made functions which can read it.
For example this one:
http://www.php.net/manual/en/function.print-r.php#93529
I hope it will help. Good Luck :)
Ended up using:
if(array_key_exists('text', $_data)){
echo 'Tweet ID = '.$_data['id_str'];
echo 'Tweet Text = '.$_data['text'];
echo '<br /><br />';
}
cheers