$cn = curl_init();
$url = 'https://URL';
curl_setopt($cn, CURLOPT_URL, $url);
curl_setopt($cn, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($cn);
$aOutput = json_decode($output, TRUE);
//var_dump($aOutput);
$curl_error = curl_error($cn);
print_r($curl_error);
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach($aOutput as $key => $data) {
var_dump($key['average_price']);
// var_dump($data[$key]["Average_Price"]);
// $sql = "INSERT INTO Market('type_id', 'average_price', 'adjusted_price')
// VALUES ($data);";
}
array(10763) {
[0]=>
array(3) {
["average_price"]=>
float(381907.23)
["adjusted_price"]=>
float(383184.18)
["type_id"]=>
int(32772)
}
[1]=>
array(3) {
["average_price"]=>
float(54090.07)
["adjusted_price"]=>
float(57340.16)
["type_id"]=>
int(32774)
}
I am attempting to add this entire multidimensional array to my database. The main thing I am having trouble with is the foreach loop.
I have tried $array[$key][$column], and many other ways but I only get NULL when dumping the variable.
I have attempted, $key['average_price'] etc still returns null.
You're getting $key and $data muddled up.
Easiest if you annotate it out:
If your $aOutput array is
array(10763) {
[0]=>
array(3) {
["average_price"]=>float(381907.23)
["adjusted_price"]=>float(383184.18)
["type_id"]=>int(32772)
}
[1]=>
array(3) {
["average_price"]=>float(54090.07)
["adjusted_price"]=>float(57340.16)
["type_id"]=>int(32774)
}
....
then
foreach($aOutput as $key => $data) {
// $key = 0
// $data = array(3) {
["average_price"]=>float(381907.23)
["adjusted_price"]=>float(383184.18)
["type_id"]=>int(32772)
}
// So what you want is $data['average_price']
You can simplify this by not even using hte key, just do
foreach($aOutput as $data) {
// $data = array(3) {
["average_price"]=>float(381907.23)
["adjusted_price"]=>float(383184.18)
["type_id"]=>int(32772)
}
// So what you want is $data['average_price']
Related
The problem is easy. The answer is not
I have an array with multiple (2) dimensions.
The code is easy (line 28-32):
<?php
foreach($select_all_data as $key => $value) {
foreach ($value as $v => $k) {
$all_values = $v.",";
}
}
?>
But when I excecute it, it shows me
Warning: Invalid argument supplied for foreach() in D:\xampp\htdocs\qlb\test.php on line 29
(I also tested $value al array with is_array, that gave me true)
An example output of $value in the loop is:
array(12) {
["id"]=>
string(3) "101"
["aangever_voornaam"]=>
string(8) "censored"
["aangever_achternaam"]=>
string(6) "censored"
["aangever_geslacht"]=>
string(3) "Male"
["pleegplaats"]=>
string(6) "censored"
["pleegdatum"]=>
string(10) "dd-mm-yyyy"
["pleegtijd"]=>
string(5) "hh:mm"
["verbalisant"]=>
string(12) "censored"
["verklaring"]=>
string(229) "censored"
["opnamedatum"]=>
string(19) "yyyy-mm-dd hh:mm:ss"
["status"]=>
string(4) "open"
["behandelaar"]=>
string(12) "censored"
}
As you can see, its a nice array that I want to put in the loop. But it gives me the invalid argument error.
What did I do wrong?
For the record: I tried to create a script to export a whole database with this script
<?php
$DB_HOST = "";
$DB_USER = "";
$DB_PASS = "";
$DB_NAME = "";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$select_all_tables = array();
$select_all_data = array();
$show_tables_from = $con->query("SHOW TABLES FROM `$DB_NAME`");
while ($row = $show_tables_from->fetch_assoc()) {
$select_all_tables[] = $row['Tables_in_'.$DB_NAME.''];
}
foreach ($select_all_tables as $a) {
$q = $con->query("SHOW CREATE TABLE `$a`");
$show_create_table[] = $q->fetch_assoc()['Create Table'];
$q = $con->query("SELECT * FROM `$a`");
$select_all_data[] = $q->fetch_assoc();
}
echo "<pre>";
//var_dump($a);
//var_dump($show_create_table);
//var_dump($select_all_data);
foreach($select_all_data as $key => $value) {
var_dump($value);
}
?>
Acording to fetch_assoc docs
Returns an associative array that corresponds to the fetched row or
NULL if there are no more rows.
So for those $value elements inside the loop that end up being null you will have that error thrown..
So just wrap it in if statement like:
if (!is_null($value)) {
foreach ($value as $v => $k) {
$all_values = $v.",";
}
}
or maybe even is_array($value) to make sure you able to iterate thru...
The arrays had a diffrent number of keys. I think because I forgot to loop the query in the first foreach (after the while)
So I changed that to
foreach ($select_all_tables as $a) {
$q = $con->query("SHOW CREATE TABLE `$a`");
$show_create_table[] = $q->fetch_assoc()['Create Table'];
$q = $con->query("SELECT * FROM `$a`");
while ($row = $q->fetch_assoc()) {
$select_all_data[] = $row;
}
}
And that was the solution!
I want to retrieve all names from my database and send it to all the registered phones by gcm.
I get an error at my android side
Error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
at reminder.com.org.remind.GCMPushReceiverService.onMessageReceived(GCMPushReceiverService.java:27)
this is the result of var_dump($message)
array(1) { ["message"]=> array(3) { [0]=> string(5) "name1" [1]=> string(5) "name2" [2]=> string(5) "name3" } }
Please help. Thanks.
PHP Server Code
<?php
include('db_connect.php');
DEFINE('GOOGLE_API_KEY','my_google_api_key');
$db = new DB_CONNECT();
$conn = $db->connect();
$gcmRegids = array();
$names = array();
$sql = "SELECT * FROM Test";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
array_push($gcmRegids, $row['reg_id']);
array_push($names, $row['name']);
}
if(isset($gcmRegids)) {
$e = "ads";
$message = array('message' => $names);
var_dump($message);
$pushStatus = sendPushNotification($gcmRegids,$message);
}
function sendPushNotification($reg_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $reg_ids,
'data' => $message,
);
$headers = array (
'Authorization: key='. GOOGLE_API_KEY,
'Content-type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($ch);
if($result === false) {
die('Curl failed:'. curl_error($ch));
}
curl_close($ch);
//echo $result;
return $result;
}
?>
array(1) { ["message"]=> array(3) { [0]=> string(5) "name1" [1]=> string(5) "name2" [2]=> string(5) "name3" } }
Android code
public class GCMPushReceiverService extends GcmListenerService {
public final static String s = "msg";
ArrayList<String> arr = new ArrayList<String>();
#Override
public void onMessageReceived(String from, Bundle data) {
if(data != null) {
arr = data.getStringArrayList("message");
Log.d("Names:",arr.get(0));
}
}
.....
}
You can't get simply an Php Array into Android/java array .. you have to convert it.. try to change your php script as..
$message = array('message' => json_encode($names));
it will convert your php array($names) into json.
than get the JSON in android as..
String message = data.getString("message");
Log.e(TAG, "Message: " + message);
now convert it into JsonArray as..
JsonArray array = new JsonArray(message);
now loop on it and get the content of Php array names.
I think here you are doing wrong.
change your code as below and try again
if (isset($gcmRegids) && count($gcmRegids) > 0) {
$e = "ads";
$message = array('message' => $names);
var_dump($message);
foreach ($gcmRegids as $gcmid) {
$pushStatus = sendPushNotification($gcmid, $message);
}
}
I'm trying to make a new column with results from an SQL query in PHP:
$someArray= array(array('match'=>'123'), array('match'=>'456'), array('match'=>'789')); //arbitrary number of elements
foreach($someArray as $key=>$item){
$someArraysDouble[]=$item;
}
$someQuery="select count(*) as somecount from sometable";
$probe1=array();
$probe2="0";
$probe3="0";
$probe4="0";
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";//myDB uses MySQL
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach($someArray as $key=>$item) {
$someQuery.=" where somecolumn like "%$item['match']%";
$blahblah=$conn->query($someQuery);
if ($blahblah->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row['match']=$item['match'];
$probe1[]=$row;
}
}
$conn->close();
}
foreach($someArraysDouble as $key1=>$item1) {
foreach($probe1 as $key2=>$item2) {
if($item2['match']==$item1['match']) {
$probe2=$item1['somecount'];
$probe3=$item2['somecount'];
$item1['somecount']=$item2['somecount'];
$probe4=$item1['somecount'];
}
}
}
The output HTML looks like this:
<html>
<head></head>
<body>
{$probe2}<br>{$probe3}<br>{$probe4}<br><br>
{loop $probe1 $key1 $item1}
{$item1['somecount']}<br><br>
{/loop}
<br><br>
{loop $someArraysDouble $key2 $item2}
{$item2['somecount']}<br><br>
{/loop}
</body>
</html>
Result is... something I don't understand:
- $probe2 is null, which is expected.
- $probe3 is the count value for last element, which is expected.
- $probe4 is the count value for last element, which is expected.
- The first loop with $probe1 produces the count value for each element, which is expected.
- The second loop with $someArraysDouble produces nothing, which is NOT expected. HOW can this happen?
For some reason that I'm not sharing in order to keep this question concise, I need to have the count value for each element outputted via $someArraysDouble.
I suspect that this line is not performing as you expect because you have not created $someArraysDouble before entering the loop:
$someArraysDouble[]=$item;
Try creating an empty array first, like this:
$someArraysDouble = array(); // <== Initialize the array first
$someArray = array(array('match'=>'123'), array('match'=>'456'),
array('match'=>'789')); //arbitrary number of elements
foreach($someArray as $key=>$item){
$someArraysDouble[] = $item;
}
See the PHP Array docs for more info, specifically the section "Creating/modifying with square bracket syntax".
Turns out it was me not understanding how foreach in PHP works.
function array_generate(){
return array(array('match'=>'123'), array('match'=>'456'), array('match'=>'789')); //arbitrary number of elements
}
$someArray=array_generate();
var_dump($someArray);
foreach($someArray as $heavy=>$load)
{
$load['addedvalue']="newvalue";
$test1[$heavy]="newvalue";
$test2[$heavy]=$load['addedvalue'];
var_dump($someArray);
}
var_dump($someArray);
var_dump($test2);
The n+2 var_dump($someArray)s (where n==count($someArray)) all show the same.
array(3) { [0]=> array(1) { ["match"]=> string(3) "123" } [1]=> array(1) { ["match"]=> string(3) "456" } [2]=> array(1) { ["match"]=> string(3) "789" } }
But var_dump($test2) shows:
array(3) { [0]=> string(8) "newvalue" [1]=> string(8) "newvalue" [2]=> string(8) "newvalue" }
This means the addedvalue of each element of $someArray does not persist once $key changes. So my solution is to use a new array, which is synced with the original array, length-wise.
var_dump($object) outputs the following result:
object(stdClass)#9 (5) {
["data"]=> object(stdClass)#8 {
["validFiling"]=> object(stdClass)#7 {
["indicators"]=> string(6) "MODE_S"
}
["plan"]=> object(stdClass)#6 {
["id"]=> string(10) "xxx"
}
}
}
In this data structure I need to access the content of the field id. I do this in the following way:
try
{
$object = $client->getPlan($p);
var_dump($object);
}
catch (Exception $e) {
print $e->getMessage();
}
$line = $client->getLastResponse();
$doc = new DOMDocument();
$doc->loadXML($line);
$data = $doc->getElementsByTagName('data');
$fp = $data->getElementsByTagName('plan');
$id = $fp->getElementsByTagName('id');
$fId = $id->item(0)->nodeValue;
And the error is (at the line $fp = $data->getElementsByTagName('plan')):
Call to undefined method DOMNodeList::getElementsByTagName()
How to solve this issue?
The error occurs because $data is a DOMNodeList which doesn't have the getElementsByTagName() method. You have the same problem with the $fp variable. If you want to access the first data element found, then change to:
$data = $doc->getElementsByTagName('data')->item(0);
$fp = $data->getElementsByTagName('plan')->item(0);
$id = $fp->getElementsByTagName('id');
Or if you want to iterate of the data elements and apply the processing to each:
$dataList = $doc->getElementsByTagName('data');
foreach($dataList as $data)
{
$fp = $data->getElementsByTagName('plan')->item(0);
$id = $fp->getElementsByTagName('id');
$fId = $id->item(0)->nodeValue;
}
The above works because its calling getElementsByTagName() on the node itself not the list.
This is the function:
function NewsDat($url="http://www.url.com/dat/news.dat", $max=5){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curlresult = curl_exec($ch);
$posts = explode("\n", $curlresult); //chop it up by carriage return
unset($curlresult);
$num=0;
$result=array();
foreach($posts as $post){
$result[] = explode("::", $post);
$num++;
if($num>$max-1){
break;
}
}
return $result;
}
var_dump(NewsDat());
Which returns:
array(5) { [0]=> array(14) { [0]=> string(10) "1183443434" [1]=> string(1) "R" [2]=> string(46) "Here is some text"...
I need to echo: 1183443434 and Here is some text...
Can anyone help?
Basic array handling?
$result = NewsDat();
echo $result[0][0]; //holds "1183443434"
echo $result[0][2]; //holds "Here is some text"
But I don't know if the values are always at this positions when you run your function.
Well as NewsDat return an array of arrays, if you need this two fields on each lines, this should do the trick:
$news = NewsDat();
foreach($news as $single_new)
{
echo $single_new[0] . " - " . $single_new[2] . "\n";
}
If you only need these two fields, just:
$news = NewsDat();
$field1 = $news[0][0];
$field2 = $news[0][2];
echo $field1 . " - " . $field2 . "\n";