Getting error while sending array to array_map function - php

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

Related

PHP get_class error converting SimpleXML to array

I have the following function which returns a SimpleXML object into a normal array. It seems to work fine, however if I turn error reporting on then I get lots of warnings say:
Warning: get_class() expects parameter 1 to be object, string given
But it still seems to be working somehow. Any ideas how I can get it to work without the errors?
function convert($content){
$data = (array)$content;
foreach ($data as $k => $v){
if(strpos(get_class($v),"SimpleXML")!==false){
$data[$k] = XMLArray($v);
}
}
return $data;
}
simply add is_object check. You are getting a warning because it is running in a loop. for some value of $v it is an object and that part is running fine but for some value $v is not an object. You are getting warning in those cases when $v is not an object.
function convert($content){
$data = (array)$content;
foreach ($data as $k => $v){
if(is_object($v) && strpos(get_class($v),"SimpleXML")!==false){
$data[$k] = XMLArray($v);
}
}
return $data;
}
I think it because of you are passing $v instead of $k
function convert($content){
$data = (array)$content;
foreach ($data as $k ){
if(strpos(get_class($k),"SimpleXML")!==false){
$data[$k] = XMLArray($k);
}
}
return $data;
}
check this

Convert an array into string or object

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.

Filtering a Multidimensional Array based of another array

I'm creating a PHP class that manipulates csv files.
As part of the class I have a function that allows the data to be filtered showOnlyWhere. However I get this error Invalid argument supplied for foreach() on line 331 (the line with the foreach statement). I tried adding global $arr; but that didn't work. How would i fix it?
$this -> rows is a multi-dimensional array that contains all the csv data.
$arr is in the format:
$key=>$val array(
$key = Column Name
$val = value that column should contain
)
Below is the showOnlyWhere function
function showOnlyWhere($arr)
{
if($this->showOnlyWhere == true){
$rows = $this->filteredRows;
}
else{
$rows = $this->rows;
}
$filter = function ($item){
global $arr; // didn't work
foreach($arr as $chkCol => $chkVal){
if ($item[$arr[$chkCol]] != $chkVal ){
return false;
break(3);
}
}
return true;
};
$this->filteredRows = array_filter($rows,$filter);
$this->showOnlyWhere = true;
}
I think the error might have something to do with the Anonymous function - but I'm not really sure.
instead of using global $arr you can make $arr available to the anonymous function via use
$filter = function ($item) use ($arr) {
//global $arr; // didn't work
foreach($arr as $chkCol => $chkVal){
if ($item[$arr[$chkCol]] != $chkVal ){
return false;
}
}
return true;
};
Also, I noticed that you are assigning $rows = $this->filteredRows; before you populate $this->filteredRows. I'm not sure if that's intentional?
Format for your $arr is wrong.
this is wrong:
$key=>$val array(
$key = Column Name
$val = value that column should contain
)
You cannot supply class objects to foreach, it should be a valid array.
It should be like this:
$arr=array(
$key => 'Column Name',
$val = 'value that column should contain'
);
So first convert your object to a valid array.

Object to String. How?

I've did some research. I've found that you can serialize then unserialize to get a string... but I want a better solution.
I got an object array returned by IMAP pear module (function imap_getmailboxes).
public function GetMailBoxes(){
$List = imap_getmailboxes($this->Link, '{'.$this->Server.':'.$this->Port.'}', '*');
$Data = array();
if(is_array($List)){
foreach($List as $Key => $Value){
$Value = unserialize(serialize($Value));
$In = strpos($Value->name, '{');
$Out = strpos($Value->name, '}');
$Part = substr($Value, $Out);
$Value->real_name = explode($Value->delimiter, imap_utf7_decode($Part));
$Value->real_name = (isset($Value->real_name[1]) ? $Value->real_name[1] : null);
$Data[$Key] = $Value;
}
}
return $Data;
}
The problem here is strpos tell me this Warning: substr() expects parameter 1 to be string, object given in /home/david/domains/davidbelanger.net/public_html/panel/drivers/mail.php on line 178.
How Can I transform the object into a string ? Any idea, never done this before.
Thanks.
I think instead of
$Part = substr($Value, $Out);
you want
$Part = substr($Value->name, $Out);
You can override the magic method __toString()
As noted here: http://www.php.net/manual/en/language.oop5.magic.php#object.tostring

PHP : foreach warning

I'am executing code :
<?php
$input="ABC123";
$splits = chunk_split($input,2,"");
foreach($splits as $split)
{
$split = strrev($split);
$input = $input . $split;
}
?>
And output that i want is :
BA1C32
But it gaves me Warning.
Warning: Invalid argument supplied for foreach() in /home/WOOOOOOOOHOOOOOOOO/domains/badhamburgers.com/public_html/index.php on line 4
chunk_split doesn't return an array but rather a part of the string.
You should use str_split instead:
$input="ABC123";
$splits = str_split($input, 2);
And don't forget to reset your $input before the loop, else it will contain the old data aswell.
It looks like http://php.net/manual/en/function.chunk-split.php returns a string, not an array. You could use str_split instead:
$input = "ABC123";
$splits = str_split( $input, 2 );
$output = "";
foreach( $splits as $split ){
$split = strrev($split);
$output .= $split;
}
As the documentation for chunk_split mentions clearly, http://php.net/manual/en/function.chunk-split.php chunk split returns a string.
foreach expects an array as first argument.

Categories