I am wanting to check if there is data present in an array of data so that I can preform a function. Would I just use in_array?
Array:
["OpenHomes"]=>
array(2) {
[0]=>
array(2) {
["Start"]=>
string(21) "/Date(1354323600000)/"
["End"]=>
string(21) "/Date(1354326300000)/"
}
Would I just do the following?
if(in_array($detail['OpenHomes']))
{
echo 'yes';
}else{
echo 'no';
}
I am wanting to check if there is anything present within OpenHomes.
try this
if(!empty($detail) && in_array('OpenHomes',$detail))
{
echo 'yes';
}else{
echo 'no';
}
you can also check by
if ($detail['OpenHomes']) {
or
if (count($detail['OpenHomes']) > 0) { ... }
Or this
if( !empty($details['openHomes']) )
{
//
}
else
{
//
}
You can also use:
count($detail['OpenHomes'])
or
sizeof($detail['OpenHomes']) // its alias, same function with different name
to get count of elements in that array, but that will count empty elements too.
Related
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));
1. Extracted from my laravel controller:
..
..
$data = json_decode($response, true);
return $data;
..
..
return view('homepage')->with('homeExclusives', $homeExclusives);
Here is a sample of the returned data, just a short version, since the returned feed is very large, but this will give you an idea of the way it's structured.
array(4) {
["success"]=> bool(true)
["status"]=> int(200)
["bundle"]=> array(2) {
[0]=> array(631) {
["StreetDirPrefix"]=> string(2) "SW"
["DistanceToStreetComments"]=> NULL
}
[1]=> array(631) {
["StreetDirPrefix"]=> string(2) "NE"
["DistanceToStreetComments"]=> NULL
}
}
I need to extract "StreetDirPrefix" value from [0] and [1], but I always get an error. Can someone help?
For the data in your example you might use array_column and specify StreetDirPrefix as the column key.
$res = array_column($array["bundle"], "StreetDirPrefix");
print_r($res);
Php demo
Without knowing what error you are getting my solution would be something like this:
<?php
if (is_array($data) && is_array($data["bundle"]) ) {
foreach ($data["bundle"] as $tmpKey => $tmpVal) {
if (isset($tmpVal["StreetDirPrefix"])) {
echo $tmpKey." => ".$tmpVal["StreetDirPrefix"]."\n";
}
}
}
?>
I always like to validate arrays, so if your $data variable or the $data["bundle"] subsection are not arrays then you will not get anything. Not even an error.
I have a working example here:
https://www.seeque-secure.dk/demo.php?id=PHP+how+to+loop+over+nested+JSON+Object
EDIT:
(if i understand you correct)
When you have validated your array all you have to do is repeat the inner validation like this:
<?php
if (is_array($data) && is_array($data["bundle"]) ) {
foreach ($data["bundle"] as $tmpKey => $tmpVal) {
if (isset($tmpVal["StreetDirPrefix"])) {
echo $tmpKey." => ".$tmpVal["StreetDirPrefix"]."\n";
}
if (isset($tmpVal["UnparsedAddress"])) {
echo $tmpVal["UnparsedAddress"]."\n";
}
if (isset($tmpVal["SalePrice"])) {
echo $tmpVal["SalePrice"]."\n";
}
//...... ect.....
}
}
?>
I have this function for parsing arguments:
function arguments($argv) {
$_ARG = array();
foreach ($argv as $arg) {
if (ereg('--([^=]+)=(.*)', $arg, $reg)) {
$_ARG[$reg[1]] = $reg[2];
} elseif (ereg('--([a-zA-Z0-0\-]*)', $arg, $reg)) {
$_ARG[$reg[1]] = 'true';
} elseif (ereg('-([a-zA-Z0-9])', $arg, $reg)) {
$_ARG[$reg[1]] = 'true';
} elseif (ereg('([a-zA-Z0-0\-]*)', $arg, $reg)) {
$_ARG[$reg[1]] = 'true';
}
}
return $_ARG;
}
After var_dump() I get something like this:
array(4) {
["xqr"]=>
string(4) "true"
["query"]=>
string(60) "Some string..."
["input"]=>
string(12) "input03.txt"
["n"]=>
string(4) "true"
}
My problem is, that I am not able to detect duplicates in parsed arguments. For example php name.php --query='Some string...' --input=input03.txt -n -n or php name.php --query='Some string...' --input=input03.txt n n. Both inputs are invalid there can be just one -n and can't be n.
Please could you help me how to handle it? Thank you
When I understand it correct you need it for argument check provided in the command line.
I would not recommend to write/invent your own function again. Use the getopt function.
It is very powerful and you can safe time!
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
This question already has answers here:
How to access a specific value in a mixed object(stdClass) and array construct?
(2 answers)
Closed 8 years ago.
var_dump($resultData);
gives me this
array(3) {
[0]=>
object(stdClass)#1 (2) {
["name"]=>
string(12) "filterName_1"
["value"]=>
string(8) "language"
}
[1]=>
object(stdClass)#2 (2) {
["name"]=>
string(9) "country_1"
["value"]=>
string(0) ""
}
[2]=>
object(stdClass)#3 (2) {
["name"]=>
string(10) "language_1"
["value"]=>
string(4) "UAE1"
}
}
How to itrate and get the values ?
tried
echo $resultData["name"];
and some other combinations but cannot make it work.
EDIT : NOTE :
As i have to get the loop of 3 items and its values i need to get the value in the loop as
for ($i=0; $i+3 <= count($resultData); $i=$i+3)
{
}
is there a way without foreach looping?
May you should try
<?php
foreach($resultData as $key => $value) {
echo $value->name; // Give you all names
}
Another example:
<?php
// Set keys you need to print
$requiredKeys = array('name', 'value');
// Iterate the array
foreach($resultData as $key => $value) {
// Iterate the required keys
foreach($requiredKeys as $reqVal) {
// Check, if propertie exists in current object
if(isset($value->{$reqVal}) {
echo $value->{$reqVal}; // Give you all names
}
}
}
Example without foreach (for-loop):
<?php
// Set keys you need to print
$requiredKeys = array('name', 'value');
// Iterate the array
for($currentElement = 0; $currentElement <= count($resultData) as $currentElement++) {
// Iterate the required keys
for($reqCounter = 0; $reqCounter <= count($requiredKeys); $reqCounter++) {
// Check, if propertie exists in current object
if(isset($resultData[$currentElement]->{$requiredKeys[$reqCounter]}) {
echo $resultData[$currentElement]->{$requiredKeys[$reqCounter]}; // Give you all names
}
}
}
$resultData is an array containing multiple objects, therefore the first object can be accessed with $resultData[0] and so on.
The objects have a property named name, which can be accessed with $object->name
If you have more than one object in the array, then you can loop through the values contained in the array with foreach. For example:
foreach ($resultData as $object) {
if($object->name === MY_NAME) {
echo $object->value;
}
}
This will take each object in the array and display its value if its name equals MY_NAME.
echo $resultData[0]->name;
Give that a try