Object to String. How? - php

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

Related

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

Warning: array_search() expects parameter 2 to be array, string given in

Here is part of my code:
$csv = file_get_contents('states.csv');
$csv = mb_convert_encoding($csv, 'UTF-8');
$json = csvToJson($csv);
$json_state = json_decode($json, true);
$bilProvin = trim($order['billing_address']['province']);
$bilCountry = trim($order['billing_address']['country']);
foreach ($json_state as $keys) {
if (array_search($bilProvin,$bilCountry, $keys)) // Added trim
{
$bilState = substr($keys['var1'], 3);
if ($bilState != 'KY') {
$order['billing_address']['province'] = $bilState;
} else {
$order['billing_address']['province'] = "";
}
}
}
How to search $bilCountry in array? from my above code shows Warning: array_search() expects parameter 2 to be array, string given in C:\xampp\htdocs\cats\index-oauth.php on line 162 as lots of lines.
Can anyone help me?
Thank you in advance!!!
Trim() returns a string. Parameter 2 is expecting an array. Maybe you can describe what you are trying to do, but if you are trying to look through a list of items put your data into an array.

Creating a function that takes arguments and passes variables

I am creating a script that will locate a field in a text file and get the value that I need.
First used the file() function to load my txt into an array by line.
Then I use explode() to create an array for the strings on a selected line.
I assign labels to the array's to describe a $Key and a $Value.
$line = file($myFile);
$arg = 3
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
This works fine but that is a lot of code to have to do over and over again for everything I want to get out of the txt file. So I wanted to create a function that I could call with an argument that would return the value of $key and $val. And this is where I am failing:
<?php
/**
* #author Jason Moore
* #copyright 2014
*/
global $line;
$key = '';
$val = '';
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$arg = 3;
$Character_Name = 3
function get_plr_data2($arg){
global $key;
global $val;
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return;
}
get_plr_data2($Character_Name);
echo "This character's ",$key,' is ',$val;
?>
I thought that I covered the scope with setting the values in the main and then setting them a global within the function. I feel like I am close but I am just missing something.
I feel like there should be something like return $key,$val; but that doesn't work. I could return an Array but then I would end up typing just as much code to the the info out of the array.
I am missing something with the function and the function argument to. I would like to pass and argument example : get_plr_data2($Character_Name); the argument identifies the line that we are getting the data from.
Any help with this would be more than appreciated.
::Updated::
Thanks to the answers I got past passing the Array.
But my problem is depending on the arguments I put in get_plr_data2($arg) the number of values differ.
I figured that I could just set the Max of num values I could get but this doesn't work at all of course because I end up with undefined offsets instead.
$a = $cdata[0];$b = $cdata[1];$c = $cdata[2];
$d = $cdata[3];$e = $cdata[4];$f = $cdata[5];
$g = $cdata[6];$h = $cdata[7];$i = $cdata[8];
$j = $cdata[9];$k = $cdata[10];$l = $cdata[11];
return array($a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l);
Now I am thinking that I can use the count function myCount = count($c); to either amend or add more values creating the offsets I need. Or a better option is if there was a way I could generate the return array(), so that it would could the number of values given for array and return all the values needed. I think that maybe I am just making this a whole lot more difficult than it is.
Thanks again for all the help and suggestions
function get_plr_data2($arg){
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return array($key,$val);
}
Using:
list($key,$val) = get_plr_data2(SOME_ARG);
you can do this in 2 way
you can return both values in an array
function get_plr_data2($arg){
/* do what you have to do */
$output=array();
$output['key'] =$key;
$output['value']= $value;
return $output;
}
and use the array in your main function
you can use reference so that you can return multiple values
function get_plr_data2($arg,&$key,&$val){
/* do job */
}
//use the function as
$key='';
$val='';
get_plr_data2($arg,$key,$val);
what ever you do to $key in function it will affect the main functions $key
I was over thinking it. Thanks for all they help guys. this is what I finally came up with thanks to your guidance:
<?php
$ch_file = "Thor";
$ch_name = 3;
$ch_lvl = 4;
$ch_clss = 15;
list($a,$b)= get_char($ch_file,$ch_name);//
Echo $a,': ',$b; // Out Puts values from the $cdata array.
function get_char($file,$data){
$myFile = $file.".txt";
$line = file($myFile);
$cdata = preg_split('/\s+/', trim($line[$data]));
return $cdata;
}
Brand new to this community, thanks for all the patience.

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.

php call array from string

I have a string that contains elements from array.
$str = '[some][string]';
$array = array();
How can I get the value of $array['some']['string'] using $str?
This will work for any number of keys:
$keys = explode('][', substr($str, 1, -1));
$value = $array;
foreach($keys as $key)
$value = $value[$key];
echo $value
You can do so by using eval, don't know if your comfortable with it:
$array['some']['string'] = 'test';
$str = '[some][string]';
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));
$value = eval($code);
echo $value; # test
However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.
Another example if you need to write access to the array item, you can do the following:
$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
$value = &$value[$segment];
}
echo $value;
$value = 'changed';
print_r($array);
This is actually the same principle as in Eric's answer but referencing the variable.
// trim the start and end brackets
$str = trim($str, '[]');
// explode the keys into an array
$keys = explode('][', $str);
// reference the array using the stored keys
$value = $array[$keys[0][$keys[1]];
I think regexp should do the trick better:
$array['some']['string'] = 'test';
$str = '[some][string]';
if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
{
if (isset($array[$keys['key1']][$keys['key2']]))
echo $array[$keys['key1']][$keys['key2']]; // do what you need
}
But I would think twice before dealing with arrays your way :D

Categories