Convert an array into string or object - php

Good day, I am trying to convert an array "$list" into string or object. I have used following methods:
<?php
include "medclass.php";
session_start();
if (isset($_SESSION['mail']))
{
$list = $_SESSION['basket'];
}
else
header("location: clientsigninpage.php?msg= Log-in First");
$obj = new med_class;
$obj->connectdb();
$val = implode(";",$list); //implode method
$val = (object) $list; //object method
$val = serialize($list); //serialize method
$result = $obj->searchMed($val);
while ($row = $result->fetchObject())
{
echo $row->MedPrice;
}
?>
With "(object)" its giving me following error: "Object of class stdClass could not be converted to string", with "implode": "Array to string conversion" and with "serialize()" it does not print anything.
The function that I am passing value is:
function searchMed($v1)
{
$sql = "select * from storepreview where MedName = '$v1'";
$ret = $this->con->query($sql);
return $ret;
}
I have used these methods by seen following links: (http://www.dyn-web.com/php/arrays/convert.php) ; (Convert an array to a string); (How to convert an array to object in PHP?)

I managed to reproduce your "Array to string conversion" error when using the implode command by running the following line of code:
implode(";", [[]]); // PHP Notice: Array to string conversion in php shell code on line 1
For converting a nested array into a string I found that a foreach loop worked:
$nestedArray = ['outerKeyOne' => ['innerKeyOne' => 'valueOne'], 'outerKeyTwo' => ['innerKeyTwo' => 'valueTwo']];
$arrayOfStrings = [];
foreach ($nestedArray as $key => $value) {
$arrayOfStrings[] = implode(",", $value);
}
implode(";", $arrayOfStrings); // string(17) "valueOne;valueTwo"
The second error associated with the line $val = (object) $list; is from trying to embed an object into the $sql string. It seems like an object is not what you want here, unless it is an object that has a __toString() method implemented.
I hope this is of some help. Using var_dump or something similar would provide more debug output to better diagnose the problems along with the above error messages. That's how I came up with the above code.

You can use json_encode to convert Array to String:
$FINAL_VALUE = json_encode($YOUR_OBJECT);
For more information, you can refer this link.

Related

How to update a decoded JSON array with new array in PHP?

I need to know how to update a decoded JSON array with new values (I don't mean a simple array_push though).
I'm going to post my code, here's my Users.json file:
[
{
"objID":"Y0FVVFZYCV",
"createdOn":{"type":"__date","date":"2018-09-21T16:48:09"},
"string":"lorem ipsum"
},
{
"objID":"YShAUqIcMg",
"username":"johndoe", // new key->value here!
"createdOn":{"type":"__date","date":"2018-09-21T16:48:14"},
"string":"lorem ipsum"
}
]
Here's my create.php file where I used to add JSON objects from a URL string:
// Prepare data to be saved:
if(!empty($_GET)){
foreach($_GET as $key => $value) {
// Random objID
$objects->objID = generateRandomID();
// Number
if( is_numeric($value) ){
$objects->$key = (float) $value;
// Boolean
} else if($value === 'true'){
$objects->$key = true;
} else if($value === 'false'){
$objects->$key = false;
// ClassName
} else if ($key === 'className'){
// String
} else { $objects->$key = $value; }
// createdOn & updatedOn Dates
$objects->createdOn = array('type'=>'__date','date'=>$formattedDate);
$objects->updatedOn = array('type'=>'__date','date'=>$formattedDate);
}// ./ foreach
// Save data into the JSON file
$jsonStr = file_get_contents($className.'.json');
// Decode the JSON string into a PHP array.
$jsonObjs = json_decode($jsonStr, true);
// Check if there's some new key and values -> update the $jsonObjs array
$result = array_diff($jsonObjs, $objects);
print_r('<br><br>DIFFERENCE: <br>'.$result[0].'<br>');
// Push array
array_push($jsonObjs, $objects);
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($jsonObjs);
file_put_contents($className.'.json', $jsonData);
// echo JSON data
echo $jsonData;
I'm trying to get the difference between $jsonObjs and $objects with array_diff():
$result = array_diff($jsonObjs, $objects);
print_r(.$result[0].'<br>');
but it dones't work, it shows an empty row and also the error_log file shows this:
PHP Warning: array_diff(): Argument #2 is not an array on line 63
I launch 2 URL strings, the first one starts with
create.php?className=Users&string=lorem%20ipsum
In the 2nd one, I add an additional string object, like this:
create.php?className=Users&string=lorem%20ipsum&username=johndoe
So, what I need to achieve is to add the "username" key into the 1st object too, as it does on the 2nd object. In other words, my Users.json file should look like this after launching the 2nd URL string:
[
{
"objID":"Y0FVVFZYCV",
"username":"", //<-- upodated key with no value
"createdOn":{"type":"__date","date":"2018-09-21T16:48:09"},
"string":"lorem ipsum"
},
{
"objID":"YShAUqIcMg",
"username":"johndoe", // new key->value here!
"createdOn":{"type":"__date","date":"2018-09-21T16:48:14"},
"string":"lorem ipsum"
}
]
As was already pointed out in the comments, you can't pass "$objects" to the array_diff function because it expects an array and "$objects" is, well, an Object.
You could cast your object to an array by calling it like this:
$result = array_diff($jsonObjs, (array)$objects);
As pointed out my #miken32, my $objects object wasn't an array, but an StdClass Object, so I simply had to replace:
$objects->
with:
$objects[$key]
In this way, $objects becomes a valid array and I can use array_diff() like this:
$result = array_diff_assoc($jsonObjs, $objects);
print_r('DIFF: '.json_encode($result).'<hr>');
It prints out a valid JSON array.

Getting error while sending array to array_map function

I am getting an error while sending an array to array_map function. Because that array contains an array inside of that.
$arr = array();
$value=array(
"result"=>$str,
"rightAnswer"=>$arr,
"tid"=>$topicId,
"view"=>$view,
);
$value = array_map('utf8_encode', $value);
This shows an error like
Message: utf8_encode() expects parameter 1 to be string, array given
parameter passed to utf8_encode should be a string. Hope the below callback function helps you to get it work.
function encode_data($val){
if(is_array($val)){
return $val = array_map('encode_data', $val);
}else{
return utf8_encode($val);
}
}
$value = array_map('encode_data', $value);
print_r($value);
Utf_encode() accept string parameter only and you are sending an array parameter
"rightAnswer"=>$arr
So thats why it is showing a warning.
$arr = '';
$value=array(
"result"=>$str,
"rightAnswer"=>$arr,
"tid"=>$topicId,
"view"=>$view,
);
$value = array_map('utf8_encode', $value);
it will work fine. I just made $arr = '' to string

How can I get in PHP the value out of an object attribute with the path stored in a variable?

For example, I have the following:
$ValuePath = "object->data->user_nicename";
And I need to print not the value of the $ValuePath but the value of the $variable->data->user_nicename that is part of a larger call .. as I have the following situation:
echo $objects->$ValuePath->details;
and is not working .. I'm getting the error Class cannot be converted to string or something when I try it like that.
PHP pseudo-code:
function get_by_path($object, $path)
{
$o = $object;
$parts = explode('->', $path);
// if you want to remove the first dummy object-> reference
array_shift($parts);
$l = count($parts);
while ($l)
{
$p = array_shift($parts); $l--;
if ( isset($o->{$p}) ) $o = $o->{$p};
else {$o = null; break;}
}
return $o;
}
Use like this:
$value = get_by_path($obj, "object->data->user_nicename");
// $value = $obj->data->user_nicename;
Check also PHP ArrayAccess Interface which enables to access objects as arrays dynamicaly
NO you cannot do that.
From your declaration $ValuePath is a variable which holds a plain string ('object->data->user_nicename') this string is not an object.
Where as,
$objects->object->data->user_nicename->details is a object.
so $objects->object->data->user_nicename->details is not same as $objects->$ValuePath->details

What does (array) $variable mean in php

I'v recently came accross a problem with some code as shown below:
$key = "upload_8_fid_aids.tmp";
public function to_key($key) {
$s = $this->table;//$s = kv
foreach((array)$key as $k=>$v) {
$s .= '-'.$this->primarykey[$k].'-'.$v;
}
return $s;
}
There's a (array)$key signature out there in the foreach loop,the first thing I'm stucking in is the "array" that prefixed with the variabls $k,what does this mean?The very first idea that hit upon me is that it converts the $k to an array,though,the variable $k is a string,is it plausible to convert string to array in php?I think it is unreasonable.So what does that array mean?
Thanks in advance!
When you cast a string to an array in PHP it becomes an array with the string pushed to it.
Example:
$test = "This is a string!";
print_r((array) $test);
Output:
Array
(
[0] => This is a string!
)
That said I find the code strange, I don't see the need for the loop, it could just be:
$key = "upload_8_fid_aids.tmp";
public function to_key($key) {
$s = $this->table; //$s = kv
$s .= '-' . $this->primarykey[0] . '-' . $key;
return $s;
}
Any type enclosed in parentheses is telling PHP to cast the following thing to that type.
In this case, it's a cheap way to avoid having to check if( is_array($key)), by just forcing it to be one.
Converting an object to an array:
<?php
/*** create an object ***/
$obj = new stdClass;
$obj->foo = 'foo';
$obj->bar = 'bar';
$obj->baz = 'baz';
/*** cast the object ***/
$array = (array) $obj;
/*** show the results ***/
print_r( $array );
?>
Result:
Array
(
[foo] => foo
[bar] => bar
[baz] => baz
)

how to cast an xml object to a associative array?

I am doing some geocoding with the google api and was wondering how do i cast the returned simplexml object? I tried the following but it does no cast the child objects.. ie.. i would like a multi dimensional array.
$url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$adr."
&sensor=false";
$result = simplexml_load_file($url);
$result = (array) $result;
You could make a JSON request rather than XML; it's recommended; unless your application requires it. Then use:
json_decode( $result, true );
http://us2.php.net/manual/en/function.json-decode.php
I found very useful this function for converting Object to Array recursively:
http://forrst.com/posts/PHP_Recursive_Object_to_Array_good_for_handling-0ka
Adapted from the site above, to use it outside classes:
function object_to_array($obj) {
$arrObj = is_object($obj) ? get_object_vars($obj) : $obj;
foreach ($arrObj as $key => $val) {
$val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;
$arr[$key] = $val;
}
return $arr;
}
Turn the SimpleXMLElement object into json and decode the json string again into an associative array:
$array = json_decode(json_encode($result), 1);
The simple cast to array does not go more deep in there, that's why the trick via json_encode and json_decode is used.

Categories