I have something like this:
array('fields' => array(
0 => array('name' => 'family_name',
'label' => 'Family Names'),
array('name' => given_names',
'label' => 'Given Names'),
array('name' => 'additional_names',
'label' => 'Additional Names'),
array('name' => 'honorific_prefixes',
'label' => 'Honorific Prefixes'),
array('name' => honorific_suffixes',
'label' => 'Honorific Suffixes')
)
)
in a variable as string. The whole thing is in one database field. If I output the variable, it is a string.
I would have an array with the content as subarrays. How do I convert this value into an array?
I searched with google, but I found explode and split and so on, but I think I miss the key word to find any solution.
Thank you for any help in this case.
Try using eval(), https://secure.php.net/manual/en/function.eval.php
eval("\$array = $string;");
print_r($array);
Your string is not built correctly to put it into the eval function. Two strings inside don't have the preceding quote and that will lead to a parse error. But you can correct it with:
$string = str_replace("=> given_names'", "=> 'given_names'", $string);
$string = str_replace("=> honorific_suffixes'", "=> 'honorific_suffixes'", $string);
After that you can use the answer of shapeshifter (please mark his answer as the correct one):
eval("\$array = $string;");
var_dump($array);
If you just look for a method to save and restore your arrays you could also use serialize / unserialize.
Related
I want to call the function from an array .My code is
$params = array(
'df' => $this->_data['df'],
'fl' => implode(',', $this->_data['fl']),
'wt' => $this->_data['wt'],
'q' => $this->_data['select'],
'sort' => '',
'fq' => implode(' ', $fq),
'indent' => 'true',
'start' => $this->_data['range'][0],
'rows' => $this->_data['range'][1],
'defType' => $this->_data['defType'],
'qf' => implode(' ', $qf),
);
i want to call function-"WordSplit" from an array:
'q' => WordSplit($this->_data['select']);
Is it possible to do this in PHP?
Thanks in Advance!!!
As has been said, "the answer is, 'yes.'" WordSplit() is a function, therefore a call to that function is a valid expression. It can be used to provide a value for an array-element.
Now, what I would do, instead, is to add a new statement after the existing one:
$params['q'] = WordSplit(params['q']);
Why? Because the very-harried person who's reading our code, someday in the future, might not notice that element 'q' is being handled differently! Purely for the sake of readability (and possible future maintainability), I would choose to do this as a separate statement. The $params array is first "assembled," in a construct where the action for every element in the array is more-or-less the same. Then, element 'q' is manipulated. (And I would place all other such "manipulations" adjacent to this one. "Clarity... Clarity...")
I have an array, like this:
)array (
'date' => '2015-12-10T00:16:58+0000',
'from' =>
array (
'name' => 'Joe Bloggs',
'user_id' => 3220562,
),
'message' => ':ip=1.1.1.1',
)
And here's my code:
$string = var_export($h, true);
echo $string;
And finally, here's what I would like to achieve:
I would like to export single strings from the array (for example I want to export 'message', and then I would get an output of ":ip=1.1.1.1").
I have tried things like $h['message'] and this doesn't work, so I'm just wondering what's the easiest / cleanest way to do this.
Any help would be greatly appreciated.
Im looking to use a PHP array obtained from a RESTful service.
They array is just a simple array outputted as follows,
array (
0 =>
stdClass::__set_state(array(
'id' => '375',
'primary_name' => 'Beaufort 3',
'price' => '',
'sqft' => '2435',
'bdrm' => '3',
'bthm' => '2.5',
'display_title' => 'Traditional A1',
'full_img_path' => '',
'thumb_path' => '',
'available_in' => 'a:2:{i:0;s:1:"2";i:1;s:1:"5";}',
'display_first' => '',
)),
)
I'm obtaining the data using file_get_contents but of course its no longer an array at this point. What is the best way to convert this back to a usable array?
I have never seen a service that provides this, probably because it is something people would avoid using, but it does look like it could be something they intend for you to be able to use with eval(). I suppose this could be intended as a convenience. I think they have made an error, though. If you use var_export, (which I assume is how this was generated) on an array like this:
$example = array (
array(
'id' => '375',
'primary_name' => 'Beaufort 3',
'price' => '',
'sqft' => '2435',
'bdrm' => '3',
'bthm' => '2.5',
'display_title' => 'Traditional A1',
'full_img_path' => '',
'thumb_path' => '',
'available_in' => 'a:2:{i:0;s:1:"2";i:1;s:1:"5";}',
'display_first' => '',
)
);
then you would get something you could eval into a variable and use in your code. However, if you var_export an array of anonymous objects instead of an array of associative arrays, you will get the type of response you are getting, which I don't know of any way to use. I would guess they are var_exporting the results of a query and they are using FETCH_OBJ instead of FETCH_ASSOC for the fetch style.
EDIT:
I was looking through the comments on var_export after writing this and came across this way of doing it that should work.
$str = str_replace("stdClass::__set_state", "(object)", $str);
eval('$array=' . $str . ';');
But just because something is possible doesn't mean we should do it.
You can convert it back into an array with eval(). http://php.net/manual/en/function.eval.php
eval('$array='.$response.';');
However, this can be dangerous, because eval will take any PHP code given it - if the service is compromised, your code would execute anything passed to it. JSON, if the service supports it, is much safer and natively supported in PHP since 5.2 via json_decode(). http://php.net/manual/en/function.json-decode.php
Sometime back I was getting alot of data via some API and I saved it into a flat file doing a simple var_dump or print_r. Now I am looking to process the data and each line looks like:
" 'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y',
'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name'
=> 'MNOP', 'email' => 'abc#example.com', 'city' => 'London',
'street_address' => 'Sample', 'first_name' => 'Sparsh',"
Now I need to get this data back into an array format. Is there a way I can do that?
What about first exploding the string with the explode() function, using ', ' as a separator :
$str = "'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => 'abc#example.com', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',";
$items = explode(', ', $str);
var_dump($items);
Which would get you an array looking like this :
array
0 => string ''middle_initial' => ''' (length=22)
1 => string ''sid' => '1419843'' (length=18)
2 => string ''fixed' => 'Y'' (length=14)
3 => string ''cart_weight' => '0'' (length=20)
...
And, then, iterate over that list, matching for each item each side of the =>, and using the first side of => as the key of your resulting data, and the second as the value :
$result = array();
foreach ($items as $item) {
if (preg_match("/'(.*?)' => '(.*?)'/", $item, $matches)) {
$result[ $matches[1] ] = $matches[2];
}
}
var_dump($result);
Which would get you :
array
'middle_initial' => string '' (length=0)
'sid' => string '1419843' (length=7)
'fixed' => string 'Y' (length=1)
'cart_weight' => string '0' (length=1)
...
But, seriously, you should not store data in such an awful format : print_r() is made to display data, for debugging purposes -- not to store it an re-load it later !
If you want to store data to a text file, use serialize() or json_encode(), which can both be restored using unserialize() or json_decode(), respectively.
Although I wholeheartedly agree with Pascal Martin, if you have this kind of data to deal with, the following (as Pascal's first suggestion mentions) could work depending on your actual content. However, do yourself a favor and store your data in a format that can be reliably put back into a PHP array (serialize, JSON, CSV, etc...).
<pre>
<?php
$str = "\" 'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => 'abc#example.com', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',\"";
function myStringToArray($str) {
$str = substr($str, 1, strlen(substr($str, 0, strlen($str)-2)));
$str = str_replace("'",'',$str);
$strs = explode(',', $str);
$arr = array();
$c_strs = count($strs);
for ($i = 0; $i < $c_strs; $i++) {
if (strpos($strs[$i],'=>') !== false) {
$_arr = explode('=>',$strs[$i]);
$arr[trim($_arr[0])] = trim($_arr[1]);
}
}
return $arr;
}
print_r(myStringToArray($str));
?>
</pre>
http://jfcoder.com/test/substr.php
Note, you would need to adjust the function if you have comma's within your array member's content (for instance, using Pascal's suggestion about the ', ' token).
It would be better and much easier to work with Serialize and Unserialize instead of var_dump.
in that form, maybe you could try a
explode(' => ', $string)
and then go through the array and put the pairs together in a new array.
As long as it's the output of print_r and an array, you can use my little print_r converter, PHP source code is available with the link.
The tokenizer is based on regular expressions so you can adopt it to your needs. The parser deals with forming the PHP array value.
You will find the latest version linked on my profile page.
i'm trying to insert an implode generated string to an array that then later be used for json implementation
the implode generated string is look like this
'id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]
i would like to used it in this code
$this->_JsonArr[]=array($Generated string);
to achieve something like this
$this->_JsonArr[]=array('id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]);
instead i got something like this
$this->_JsonArr[]=array(" 'id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]");
seem like generated string is treated as one element as key and value pair.
obviously i can get expected output from mysql because of this, can anybody help me with this
Why do you need to implode anything? Just pass the array:
$this->_JsonArr[] = your-non-imploded-array-here;
I think a full solution to what you want to do is something like this (i.e., the third code box in your question):
$row = array(
'id' => $this->_SqlResult[0],
'UserId' => $this->_SqlResult[1],
'Msg' => $this->_SqlResult[2],
'MsgStamp' => $this->_SqlResult[3]
);
$this->_JsonArr[] = $row;
$this->_JsonArr[]=array($Generated
string);
Looks like you want use arrays keys and values, but as I see you put into array plain string with expectation that array parse your plain string in format: keys => values.
You can try create array like below:
$this->_JsonArr[ $Generated_key ] = array( $Generated_value );
(Please correct me if I wrong understand your question).