PHP append each element in an array - php

I'm having a difficult time appending each element in an array I have in PHP for multiple OneSignal tags. Here is the result of my current JSON encoded array:
[{"value":"email#address.com"},
{"value":"email#address.com"},
{"value":"email#address.com"}]
Desired output:
[{"key":"user_email","relation":"=","value":"email#address.com"},
{"key":"user_email","relation":"=","value":"email#address.com"},
{"key":"user_email","relation":"=","value":"email#address.com"}]
Here is my current PHP code:
$jsonData = array();
$allStaffInit = mysql_query("Select * from users");
while ($staffrow = mysql_fetch_object($allStaffInit)){
$jsonData[] = $staffrow;
}
echo json_encode($jsonData);
Any help is greatly appreciated! Thanks!

Try replacing
$jsonData[] = $staffrow;
with
$object = new stdClass();
$object->key = "user_email";
$object->relation = "=";
$object->value = $staffrow->value;
$jsonData[] = $object;
I am typing this in a browser, so cannot test, but you get the idea (if you don't get the idea, ask in comments :)

If you must use the mysql_ functions, you don't need to manually construct an object or array, just get the result set as an array and use that.
while ($staffrow = mysql_fetch_assoc($allStaffInit)){
$jsonData[] = $staffRow;
}
But I seriously recommend you at least upgrade to using the mysqli extension instead. You won't really have to adjust your code much.
http://php.net/manual/en/book.mysqli.php

Related

extract specific data from array in mysql database using php

This is the data that i need to extract like example profile_contact_numbers
so the output will be +639466276715
how can i do it in php code??
any help will do regards
a:2:
{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}
I'm not sure 100% this can go into an array but try the unserialize function
$json_resp = {your values};
$array[] = unserialize($json_resp);
To check if it has gone into an array print_r on $array.
Read this link if the code above doesn't work
http://php.net/manual/en/function.unserialize.php
I have managed to fix it
$serialized = array(unserialize('a:2:{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}'));
var_dump($serialized);
use code :
$var = preg_split('["]','{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}');
echo $var[1].'='.$var[3]; // profile_contact_numbers=+639466276715
echo $var[5].'='.$var[7]; // profile_position=Courier

Reference specific row's column value from array

I have read a-lot of answers on this but they don't seem to be working.
I have the following code:
$amountoflikes=mysql_query("SELECT * FROM `uc_likes` WHERE `dwable` = '372'");
This returns the following:
If I wanted to echo the value of dwable in the 2nd row for instance (not involving the initial query).
I've tried:
while($row3 = mysql_fetch_assoc($amountoflikes)){
$json[] = $row3;
}
echo json_encode($json);
But this returns null.
I'm currently using PHP 5.5 (native).
I'm not using MySQLi or MySQL PDO.
Can someone tell me where I'm going wrong. Ideally I'd prefer not to use a loop but I don't know if that's possible.
Thanks!
Try declaring $json as an array above the while:
$json = array();
declare your array as follows
$json = array();
and see if you have results before your result
if ($amountoflikes)
{
while(){...}
}

How do I deal with this type of returned JSON in PHP?

I have an API call that's returning JSON that looks like this:
{"subtotal":{"amount":"0.50","currency":"USD"}}
I'm not sure how to access the 'amount' variable. I tried
$jsonObject = json_decode(returnJSON);
$amount = $jsonObject->{'subtotal'}->{'amount'}
but that doesn't work. How is this data accessed?
You can access it as an associative array:
$jsonObject = json_decode($returnJSON, true);
$amount = $jsonObject['subtotal']['amount'];
http://php.net/manual/en/function.json-decode.php
Try this
$returnJSON = '{"subtotal":{"amount":"0.50","currency":"USD"}}';
$jsonObject = json_decode($returnJSON, true);
$amount = $jsonObject['subtotal']['amount'];
or
$returnJSON = '{"subtotal":{"amount":"0.50","currency":"USD"}}';
$jsonObject = json_decode($returnJSON);
$amount = $jsonObject->subtotal->amount;
As opposed to all these other comments, you can also just use it as a regular object (which is json_decode's default):
$jsonObject = json_decode($returnJSON);
$amount = (float)$jsonObject->subtotal->amount;
var_dump($amount); //float(0.50)
All that you need is here:
http://php.net/manual/en/function.json-decode.php#example-3736
Check the first example.
What does not work? What's the error message? Do you get a
Trying to get property of non-object in MyPath\myPHPFile on line 3
error message?
In that case it's because your JSON is flawed, there's a closing bracket missing. After fixing that it works on my side to access it the way you want.
Also, don't forget to close each line with a semicolon in PHP.

getting a value of a known key in php failing

I know it's my syntax, but can't find the problem.
I normally use a loop to turn any json keys into variables like this:
Sent JSON: [{\"name\":\"dolly\",\"page\":\"A4\"}]
$object = json_decode(stripslashes($_POST['myData']));
foreach ($object[0] as $key => $value)
{
$$key = preg_replace('/--+/',' ',$value);
}
So now, eg, I have $page = "A4". Works fine.
Now, rather than looping through like that, I just want to access the 'page' key (that I know is going to be there every time), and disregard anything else.
I thought this would do it, but it falls over with "Cannot use object of type stdClass as array":
$object = json_decode(stripslashes($_POST['myData']));
$page = $object[0]['page'];
This doesn't error out, but it returns nothing:
$object = json_decode($_POST['myData']);
$p = $object[0]->page;
As does
$p = $object->page;
What am I screwing up here?
Thanks for taking a look.
This seems to work fine for me?
$a='[{\"name\":\"dolly\",\"page\":\"A4\"}]';
$o=json_decode(stripslashes($a));
var_dump($o[0]->page);
string(2) "A4"
Does that help?
You will need to combine your approaches ;-)
$object = json_decode(stripslashes($_POST['myData'])); // note the stripslashes() here!
$p = $object[0]->page;
As the object encoded is an array, you do need to get the first element and then the object property as you did in your second snippet of code. You just forgot to apply stripslashes() so that json_decode() failed.

PHP treats an array as an object

I'm not a PHP developer so I may be doing something wrong. I'm trying to decode JSON string and insert some values to mysql database. I'm getting a valid array of json objects (tested with jsonlint), so I'm adding them one by one to database. But php throws :
<b>Fatal error</b>: Cannot use object of type stdClass as array error.
This is the code :
$array = json_decode(stripslashes($_POST['data']));
for($i = 0, $l = sizeof($array); $i < $l; $i++){
$obj = $array[$i];
echo "ARRAY1: ".$array;
echo "L: ".$l;
echo "ARRAY2: ".gettype($array);
$q = 'INSERT INTO dependencies SET projectID = "1", `from` = "'.$obj->{'From'}.'", to = "'.$obj->{'To'}.'", type = "'.$obj->{'Type'}.'", cls = "'.$obj->{'Cls'}.'", lag = "'.$obj{'Lag'}.'"';
Error is thrown from line $q = 'INSERT INTO... and the printed variables show that indeed my $array is an Array :
ARRAY1: ArrayL: 2ARRAY2: array . What am I doing wrong here ?
json_decode returns an object, unless you specify you want an array with the second optional argument:
json_decode(stripslashes($_POST['data']), true);
Some other useful advice:
Use var_dump for debugging purposes. It will help you understand the structure of any objects/arrays in your code.
You should not be accepting data through post and the using it in an SQL query without any sanitation, anyways. I highly recommend you fix that asap.
You're missing a -> in the last assignment:
$obj{'Lag'}
The simplest way is as Paul pointed out and I'd advise this one. But if you ever need to cast an array as an object use:
$newObject = (object) $oldArray;

Categories