How to distinguish between array and non-array output - php

I'm working on a way to pull a list of files from a query and am having trouble when the query returns more than one file.
<?php
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors',1);
static $fileCount = 0;
date_default_timezone_set('UTC');
ob_start();
$soapClient = new SoapClient("https://ip_address:8443/CDRonDemandService/services/CDRonDemand?wsdl",
array("login" => "login","password"=> "password","trace" => true, "cache_wsdl" => WSDL_CACHE_NONE));
echo '<pre>';
//THIS LINE IS FOR A MANUAL PULL OF THE LIST. ENTER THE START AND END DATES AS NEEDED
$data = $soapClient->get_file_list("beginning_range","end_range","1");
//If $data only contains one object, execute this;
if (count($data) === 1)
{
var_dump($data);
$name = $data->FileName;
echo '<tr><td>'. $name .'</td></tr>';
$fileCount = '1';
}
//Otherwise, execute this if $data contains any other number
else
{
sort($data->FileName);
var_dump($data);
foreach($data->FileName as $name)
{
echo '<tr><td>' . $name . '</td></tr><br>';
$fileCount++;
}
}
echo "<TABLE>";
$content = ob_get_clean();
echo "Number of CDR Files <b>" . $fileCount . "</b><br />";
echo $content;
?>
This code works okay when the output of a query contains a single file. This is the output;
object(stdClass)#2 (1) {
["FileName"]=>
string(40) "file_1"
}
file_1
But when the output contains multiple files (an array), this is the output;
object(stdClass)#2 (1) {
["FileName"]=>
array(2) {
[0]=>
string(40) "file_1"
[1]=>
string(40) "file_2"
}
}
Notice: Array to string conversion in /var/www/test.php on line 49
Array
If I remove the code in the if statement and leave only the code in the else statement, I'm able to pull the list of files;
object(stdClass)#2 (1) {
["FileName"]=>
array(2) {
[0]=>
string(40) "file_1"
[1]=>
string(40) "file_2"
}
}
file_1
file_2
It looks to me that the If/Else structure isn't right, but I'm not sure how to go about correcting it. Also, the var_dump statements are only there for troubleshooting, to show that I am actually pulling information, I will remove it later. Any help is appreciated.

Looks like count($data) is always equal to 1. You're trying to access an array with $data->FileName. Which is throwing the error
if (count($data)) {
if(is_array($data->FileName)) {
foreach($data->FileName as $name) {
echo '<tr><td>' . $name . '</td></tr><br>';
$fileCount++;
}
} else {
echo '<tr><td>'. $data->FileName .'</td></tr>';
$fileCount++;
}
} else {
echo "no files!";
}

Maybe it will work if you change
if (count($data) === 1)
to
if (count($data->Filename) === 1)

change this:
if (count($data) === 1) { ... }
to this:
if ( is_array($data->Filename) ) { ... }
documentation

Related

I got a working array but my code isn't working to display each row of multidimensional array

I am using a working function that perfectly displays the contents of a csv file.
function csv2array( $filename, $delimiter )
{
// read the CSV lines into a numerically indexed array
$all_lines = #file($filename);
if( !$all_lines )
{
return FALSE;
}
$csv = array_map( function( &$line ) use ( $delimiter )
{
return str_getcsv( $line, $delimiter );
}, $all_lines );
// use the first row's values as keys for all other rows
array_walk( $csv, function( &$a ) use ( $csv )
{
$a = array_combine( $csv[0], $a );
});
array_shift( $csv ); // remove column header row
return $csv;
}
$items = csv2array( 'filetest.csv', ';' );
//print_r( $items );
echo '<pre>';
var_dump( $items );
echo '</pre>';
The var_dump output is perfect and displays:
array(40) {
[0]=>
array(4) {
["Jurisdiction"]=>
string(2) "AL"
[" Total Distance(mi.)"]=>
string(7) "1730.68"
[" Off Road(mi.)"]=>
string(4) "2.63"
[" Toll Road(mi.)"]=>
string(1) "0"
}
[1]=>
array(4) {
["Jurisdiction"]=>
string(2) "AR"
[" Total Distance(mi.)"]=>
string(6) "826.27"
[" Off Road(mi.)"]=>
string(4) "1.35"
[" Toll Road(mi.)"]=>
string(1) "0"
}
[2]=>
array(4) {
["Jurisdiction"]=>
string(2) "DE"
[" Total Distance(mi.)"]=>
string(5) "49.11"
[" Off Road(mi.)"]=>
string(4) "0.34"
[" Toll Road(mi.)"]=>
string(4) "6.57"
}
I am trying to display the values of those $rows which sounds super easy but I am getting empty values and searched the internet and cannot find the right way to do it. Here is my code:
foreach($items as $row)
{
echo $row[0]. " ".$row[1]." ".$row[2]."TESTTEST<br>";
}
but I only get the TESTTEST results but the total number of times it displays TESTTEST is correct but the values are empty so what am I missing? I searched this site and others and they seem easy but mine isn't working. Thanks.
What you could do is nest the loop or implode it.
Nesting:
foreach($items as $row)
{
foreach($row as $val){
echo $val . " ";
}
echo "TESTTEST<br>";
}
Or implode:
foreach($items as $row)
{
echo implode(" ", $row);
echo "TESTTEST<br>";
}
You shouldn't use a numerical index for the data as you've just added the column name as the index.
But you can just implode() the data anyway...
foreach($items as $row)
{
echo implode(" ", $row)."TESTTEST<br>";
}
Thanks for the help everyone I got it the way I want and can expand from here on out. I was looking for this code:
$i = 0;
foreach($items as $row)
{
echo $row['Jurisdiction'] . $row[' Total Distance(mi.)'] . "TESTTEST<br>";
$i++;
}
echo 'total: ' . $i;
I will be sure to trim out the space on the names.

Why do JSON values not display in PHP?

I am working PHP and MySQL. I am created a database and table. I want to convert table to JSON. So, I write this code block:
<?php
include "../config/database.php";
$SQLUser = "SELECT * FROM tbl_user";
$SQLUserResult =mysqli_query($Conn,$SQLUser );
$JSON= array();
while($row=mysqli_fetch_assoc($SQLUserResult ))
{
$JSON[] = $row;
}
$Show = json_encode($JSON);
echo count($JSON);
echo $Show;
?>
When run this page, I take JSON size correctly. But I can't display JSON values. What can I do?
In the page source, I see the count of rows in my JSON array (13), but no data.
Adding var_dump($row); shows me something like
array(13) { [0]=> array(3) { ["id"]=> string(1) "1" ["name"]=> string(1) "A" ["surname"]=> string(1) "A" } [1]=> array(3) { ...
The encoding is utf8_general_ci.
I think, your database or tables returns probably a faulty response, some strings were probably not UTF-8. So, You can create a function for convert UTF-8.
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
Than, you can encode just like this:
echo json_encode(utf8ize($JSON));

Iterating through rangeToArray() in PhpSpreadsheet

I have Excel sheets that I need to perform calculations with.
I am using PHPSpreadsheet to read and write, as PHPExcel is now deprecated.
The problem I am experiencing is in getting values from a specific column to perform calculations.
After going through the documentation, I found that I can use the rangeToArray() function to retrieve the values.
My code looks like this:
$inputFiletype = 'Xlsx';
$inputFileName = './helloworld.xlsx';
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
$find_val = $spreadsheet->getActiveSheet()->rangeToArray('K1:K5');
This, according to the documentation, creates an array ($find_vals).
However, when I attempt to loop through the array to view the values, I get an 'Array to string Conversion' notice, with the output of "Array".
If I use var_dump, I get the following:
array(5) { [0]=> array(1) { [0]=> float(1) } [1]=> array(1) { [0]=> float(2) } [2]=> array(1) { [0]=> float(3) } [3]=> array(1) { [0]=> float(4) } [4]=> array(1) { [0]=> float(5) } }
I have tried the following loop codes:
for($i=0; $i<=4; $i++) {
echo (string)$find_val[$i];
}
as well as
foreach($find_val as $vals) {
echo $vals;
}
I have also tried the following which changed the result a little:
for($i=0; $i<=4; $i++) {
echo (string)$find_val[$i][$i];
}
This output one value, and gave me Undefined Offset errors for the other 4 iterations.
How would I be able to successfully iterate through a rangeToArray value using the PhpSpreadsheet API?
Thanks in advance.
Similar answer here
foreach ($find_val as $cell) {
foreach ($cell as $finalValue) {
echo $finalValue . "\r\n";
}
}
Just saw your post now. Have you tried this?
You are almost there.
foreach($sheetData as $vals) {
echo $vals[0];
}

Advanced PHP loop

I get translations from database and want to get generate it in Javascript object, like:
var Lang = {
eng: {
txtUserName: 'Username',
txtLogout: 'Logout'
},
dnk: {
txtUserName: 'Brugernavn',
txtLogout: 'Afslut'
}
}
I got stuck in loops, the result I get is not what I need.
This is my PHP:
var Lang = {
<?php
$allLangs = $this->params->getLanguages;
foreach ($allLangs as $allLang) :
echo $allLang->lang_code . ': ';
echo '{';
foreach ( $translationsall as $translation ) :
if ( $translation['it_text'] == 'txtUserName' ) :
for ( $i = 1; $i <= 1; $i++ ){
var_dump($translationsall[$i]);
}
endif;
endforeach;
echo '},';
echo "\r\n";
endforeach;
?>
}
And this is what I get:
var Lang = {
dnk: {array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
},
eng: {array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
}
How can I edit my loops to get result I need?
Maybe there is a smarter way to generate Lang object?
And, forgot to mention that I need only few translations, that's why I have this in PHP if:
if ( $translation['it_text'] == 'txtUserName' ) :
//stuff
endif;
Any ideas are welcome :)
And this what I get from var_dump($translationsall):
array(2748) {
[0]=>
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "CMS"
}
[1]=>
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "CMS"
}
[2]=>
array(2) {
["it_text"]=>
string(9) "txtLogout"
["it_name"]=>
string(6) "Afslut"
}
[3]=>
array(2) {
["it_text"]=>
string(9) "txtLogout"
["it_name"]=>
string(6) "Logout"
}
[4]=>
array(2) {
["it_text"]=>
string(10) "btnRefresh"
["it_name"]=>
string(9) "Hent Igen"
}
[5]=>
array(2) {
["it_text"]=>
string(10) "btnRefresh"
["it_name"]=>
string(7) "Refresh"
}
}
Please, don't do this. - Make an API call to a PHP backend producing the data you need. - Using either out of the box functions such as $.ajax from jQuery or other prebuilt frameworks will help you achieve this.
If you still want to go down the line of dynamically doing this (your question) - remove var_dump - which is ultimately dumping the type and other details (as it should) and use foreach (key, value) which will help you generate what you need. - But rather going down this dodgy route I'd recommend you take a look at how to serve an API using Laravel or other frameworks.
You could pass data from PHP to JS with JSON.
From PHP, you can use json_encode():
echo json_encode($translation);
And in your JS use JSON.parse():
var obj = JSON.parse('{"key":value}');
You can then do:
<?php
$allLangs = $this->params->getLanguages;
$json = json_encode($allLangs);
?>
<script>
var Lang = JSON.parse('<?php echo $json; ?>');
</script>
As others here have already mentioned; it is a bad idea to dynamically create your javascript like this - I would instead use JSON to serialize and deserialize the data. Anyway, if you insist on dynamic creation; it'll probably be something along the lines of;
var Lang = {
<?php
$allLangs = $this->params->getLanguages;
foreach ($allLangs as $allLang) {
echo $allLang->lang_code . ': {';
foreach ( $translationsall as $translation ) {
$total_words_to_translate = count($translation);
for($i = 0; i <= $total_words_to_translate; $i++){
if ( $translation['it_text'] == 'txtUserName' ){
print("txtUserName: ".$translationsall[$i]);
}
if ( $translation['it_text'] == 'txtLogout' ){
print("txtLogout: ".$translationsall[$i]);
}
}
}
echo '},';
echo "\r\n";
}
?> }
Its somewhat hard to determine the exact code when we don't know the structure / naming conventions of your database / variables.
Use json_encode:
var Lang = <?php
$all_langs = $this->params->getLanguages();
echo json_encode($all_langs);
?>;
Not sure how close I am with the data definitions, but I've included them so you can see what I'm assuming and hopefully be able to adjust it to your needs.
The way it works is that it starts at the beginning of $translationsall array and assumes that the $allLangs array is in the same order as the entries ( so in this case the dnk and then the eng values). These it then populates into the output under the language key, with it_text as the key and it_name as the translation.
$translationsall = [["it_text" => "txtLogout", "it_name"=>"Afslut"],
["it_text"=> "txtLogout", "it_name"=> "Logout"],
["it_text" => "txtLogout2", "it_name"=>"Afslut2"],
["it_text"=> "txtLogout2", "it_name"=> "Logout2"]
];
$allLangs = [ (object)["lang_code"=> "dnk"], (object)["lang_code"=> "eng"] ];
$countTrans = count($translationsall);
$out = [];
$i = 0;
while( $i < $countTrans ) {
foreach ( $allLangs as $language ) {
$out[$language->lang_code][$translationsall[$i]["it_text"]] = $translationsall[$i]["it_name"];
$i++;
}
}
echo json_encode($out, JSON_PRETTY_PRINT);
This prints out
{
"dnk": {
"txtLogout": "Afslut",
"txtLogout2": "Afslut2"
},
"eng": {
"txtLogout": "Logout",
"txtLogout2": "Logout2"
}
}
You can try with echo see bellow code :
var Lang = {
<?php
$allLangs = $this->params->getLanguages;
foreach ($allLangs as $allLang) :
echo $allLang->lang_code . ': ';
echo '{';
foreach ( $translationsall as $translation ) :
if ( $translation['it_text'] == 'txtUserName' and $translation['itl_lang_code '] == $allLang->lang_code) :
echo "txtUserName:'".$translation['it_text']."',txtLogout:'".$translation['it_name']."' ";
endif;
endforeach;
echo '}';
echo '},';
echo "\r\n";
endforeach;
?>
}

How to Filter API array objects response

$storiesResponse = $login->getStoriesResponse();
if (strpos($storiesResponse, 'mzaboss') == false) {
echo "mzaboss is not available! die! \n";
die;
} else {
foreach($storiesResponse->getFriendStories() as $friendStories){
$friendStoriesUsername = $friendStories->getUsername();
$storiesContainer = $friendStories->getStories();
foreach($storiesContainer as $storyContainer){
$story = $storyContainer->getStory();
echo "Mark as viewed story ID: " . $story->getId() . "\n";
$snapchat->markStoryViewed($story->getId());
}
$account_id = $i + 1;
// return true;
}
}
}
The API response:
object(X\API\Response\Model\FriendStories)#14161 (2) {
["username":"X\API\Response\Model\FriendStories":private]=>
string(7) "mzaboss"
["stories":"X\API\Response\Model\FriendStories":private]=>
array(1) {
[0]=>
object(X\API\Response\Model\FriendStoryContainer)#14166 (2) {
["story":"X\API\Response\Model\FriendStoryContainer":private]=>
object(X\API\Response\Model\Story)#14168 (16) {
["id":"X\API\Response\Model\Story":private]=>
string(21) "mzaboss~1467880186851"
["username":"X\API\Response\Model\Story":private]=>
string(7) "mzaboss"
["mature_content":"X\API\Response\Model\Story":private]=>
bool(false)
["client_id":"X\API\Response\Model\Story":private]=>
string(44) "MZABOSS~E02D10B1-9D0B-4698-A9E8-EB43F4D4281D"
["timestamp":"X\API\Response\Model\Story":private]=>
int(1467880186851)
["media_id":"X\API\Response\Model\Story":private]=>
string(16) "6315314297815040"
["media_key":"X\API\Response\Model\Story":private]=>
string(44) "Z0xvmwDCcY3leDm3DC4QPdOGh+9va4iYEbb0Zs0YkUQ="
["media_iv":"X\API\Response\Model\Story":private]=>
string(24) "C+omyS1YQncoraMO0iY4jg=="
["thumbnail_iv":"X\API\Response\Model\Story":private]=>
string(24) "WB4E4e0w0ToXZOqBI+z87w=="
["media_type":"X\API\Response\Model\Story":private]=>
int(0)
["time":"X\API\Response\Model\Story":private]=>
float(3)
["caption_text_display":"X\API\Response\Model\Story":private]=>
NULL
["zipped":"X\API\Response\Model\Story":private]=>
bool(false)
["time_left":"X\API\Response\Model\Story":private]=>
int(86296613)
["needs_auth":"X\API\Response\Model\Story":private]=>
bool(false)
["is_shared":"X\API\Response\Model\Story":private]=>
bool(false)
}
["viewed":"X\API\Response\Model\FriendStoryContainer":private]=>
bool(false)
}
}
}
$storiesResponse is very long array objects. I want to find if "mzaboss" is in that array object response or not, if it exists then good, if it not there, then die.
But getting always error:
PHP Warning: strpos() expects parameter 1 to be string, object given in /home/mzapc/test/asstest/adder/marker/marker.php on line 143
mzaboss is not available! die!
Either mzaboss is there or not. it will die!
any help?, thanks.
You have $storiesResponse as an array not a string. So you should use in_array() except strpos().
The strpos() function finds the position of the first occurrence of a string inside another string.
And, in_array() checks if a value exists in an array.
$storiesResponse = $login->getStoriesResponse();
if (in_array('mzaboss', $storiesResponse)) {
foreach($storiesResponse->getFriendStories() as $friendStories){
$friendStoriesUsername = $friendStories->getUsername();
$storiesContainer = $friendStories->getStories();
foreach($storiesContainer as $storyContainer){
$story = $storyContainer->getStory();
echo "Mark as viewed story ID: " . $story->getId() . "\n";
$snapchat->markStoryViewed($story->getId());
}
$account_id = $i + 1;
// return true;
}
}
else {
echo "mzaboss is not available! die! \n";
die;
}
$storiesResponse = $login->getStoriesResponse();
foreach($storiesResponse->getFriendStories() as $friendStories){
if($friendStories->getUsername() == "mzaboss"){
echo "debugger - mzaboss found\n";
$friendStoriesUsername = $friendStories->getUsername();
$storiesContainer = $friendStories->getStories();
foreach($storiesContainer as $storyContainer){
$story = $storyContainer->getStory();
echo "Mark as viewed story ID: " . $story->getId() . "\n";
$snapchat->markStoryViewed($story->getId());
}
$account_id = $i + 1;
// return true;
}
This going to work.
But I want it if "mzaboss" not there I want to pause the code for 5mins, then relogin to first account again.

Categories