I've been working on a very large, complicated framework I'm writing. I have used a process similar to this one for two other packages, and it worked flawlessly, however this str_replace is giving me trouble.
This is a small snippet from a much larger function. The function this particular snippet is from replaces the default value in a config file to a value dependent on user input. I'm not going to include all the other various string replacements that go on in this function, nor am I going to detail the script which grabs the contents of the config file and writes it. The issue is isolated to this snippet. I know so because this snippet replicates the issue in the larger function when it is isolated in a test file.
The equivilent code is...
<?php
$new_table_array = '$ecom_tables = [
"product" => "test1",
"promo" => "test2",
"records" => "test3"
];';
$test = str_replace("$ecom_tables = [];", $new_table_array, '
$ecom_tables = [];
');
?>
That snippet is formatted identically to the real function. The result of this snippet in the function, and in the test file is...
$ecom_tables$ecom_tables = [
"product" => "test1",
"promo" => "test2",
"records" => "test3"
];
I have looked over my concatenations, and insured that all of my string quotations are in the correct place. It passes the syntax check, and also runs when I load the test page, however the result is always unexpected.
Why is str_replace only replacing part of the string I specified with the new value?
Related
I have issue to run mongodb query in php language while its working fine and return result in console but when I try to implement in PHP language it return blank array.
Please let me know what could be issue?
Below query is Working fine in console
db.mp_ms_details.find({
$or : [
{"title": /.*पंचायत*/},
{"description": /.*पंचायत*/}
]
})
Mongodb Query with PHP
$cursor = $collection->find(array('$or' => array(
array("title" => "/.*पंचायत*/"),
array("description" => "/.*पंचायत*/")
)));
$response = $cursor->toArray();
echo count($response);die;
When you are running directly in MongoDB, you are using regex expression :
{"title": /.*पंचायत*/}
See, there are no quotes in the value field. But when you are running this through PHP, you are providing a String value :
array("title" => "/.*पंचायत*/")
So in the first query, you are looking for documents where title field contains (and not equals) पंचायत, while in the second query you are looking for documents having the exact title "/.पंचायत/"
For your use case:
array("title" => new MongoRegex("/.*पंचायत*/i"))
$requestParams = [ 'aame_uuid' => 'aba627', 'currency' => 'TEST'];
ksort($requestParams);
$hashString = http_build_query($requestParams);
var_dump( $hashString);
gives
string(30) "aame_uuid=aba627¤cy=TEST"
so why does currency transformed to ¤cy , how can correct it ?
I think the problem is the ¤ html code.
http://character-code.com/currency-html-codes.php ¤ gets replaced to this char.
Maybe you should add an specific seperator like &
to the http_build_query to make sure it will replaced to foo.php?aaaa_uid=aba627¤cy=Test
I just tested your code and I get the following string back:
C:\wamp64\www\test\test.php:8:string 'aame_uuid=aba627¤cy=TEST' (length=30)
It seems to be working fine for me. Have you tried using some other key? If it gives somewhat the same result your file or server could be corrupt.
If not the word curren might be presaved as a function to do something (which is highly unlikely). Did you mistype it as currentcy maybe (current is a php function)?
I'm fairly new to json, and I'm having an issue with json_decode. I think I know why, but I haven't been able to sort out how to fix it.
Basically, I have a URL that supplies json info. I grab it using cURL, and return it as a PHP variable, and that's working just fine. I can print_r out all the info I want. However, when I use json_decode($json, true), it returns NULL.
I THINK it's because, technically, what's being returned is not a string, but more like an object - and I can't sort out how to grab the contents of that object.
For example, when I return the json stuff as a php variable:
print_r($json);
The output returned looks like so (I won't do it exactly, because it's HUGE, so I'll show you the layout to keep it simple)
MyThing.returnedItems({MyThing.returnedItems({
"projects":[{
"completed":"2010-12-21",
"status":"finished",
"favorited":0,
"started":"2010-12-20",
"percentage":78,
"permalink":"slug to post",
"size":"One size",
"thumbnail":{"src":"full path to full size image",
"medium":"full path to thumbnail"},
"name":"Some title here",
"notes":"description here",
"url":"URL to page",
"comments":0},
So you can see it's like a nested array. I don't mind that, but I'd like to be able to access all the key/value pairs of these arrays as PHP variables. But it seems because of the "MyThing.returnedItems()" surrounding it, it doesn't see it as a string to decode, so I get a NULL value every time.
Anyone know what I'm missing here? Once I figure out how to grab the stuff inside there, I think I've got it (simple foreach or whatnot to get the rest of the variables as needed), but I just can't seem to get in there.
This is valid JSON
{
"item1": [
{
"something": [],
"something else": "some value"
}
],
"another fun thing": [
{
"more fun": "fun value 1",
"even more!": "fun value 2"
}
],
"item2": {
"another thing": "another value"
}
}
This is not!
MyThing.returnedItems({
"item1":[{"something:[],
"something else": "some value"},
"another fun thing": [{"more fun": "fun value 1",
"even more!": "fun value 2"}]
],
"item2":{"another thing": "another value"}
})
Its a javascript method call
Okay, I just wanted to add that you all REALLY helped me out. Especially MaX, because by knowing the "official term" of what was happening, I had better searches and ended up finding some really interesting code that eventually landed me my solution. However, I did discover the reason why I was having my json wrapped in that weird function method call: the URL that the site gave me to access their API actually had that call in it, so it was returned wrapped in it. In other words, the json file URL I had was like so:
somesite.com/apicall.json?key=1234567890&callback=MyThing&version=0...
so as soon as I removed that "callback" section - BAM the json was no longer wrapped, and a whole new world of foreach functions opened up to me. So, even though the solution ended up being a REALLY stupid oversight on my part, I wanted to thank you all for your input, because I learned a whole lot of stuff I wasn't planning to today XD
Oh, and the code that actually ended up working (after I got rid of the callback part of the URL, because json_decode was still returning NULL on me) was this:
$data = json_decode(file_get_contents($json), true);
print_r($data); // array of everything available for me to mess with!
Thanks again for your help, everyone :) I REALLY appreciate it!
How to generate json response using php
In the model:
public function groups($getGroupId) {
$cols = array('group_id','name');
$sql = $this->select ()
->from ( $this->_name, $cols )
->where ( 'parent_id=?', $getGroupId );
$groupDetails = $this->fetchAll ( $sql );
//$childGroupName = $groupDetails['name'];
return $groupDetails;
}
groupDetails.php page:
$dbGroup = new dbGroups();
$groupDetails = $dbGroup -> groups($getGroupId);
$jsonResponse = json_encode($groupDetails);
print_r($jsonResponse);
When printing the data i'm getting response like this
[{"group_id":"2","name":"ABCD"},{"group_id":"7","name":"XYZ"}]
But i want output like this, Because i have to generate a jstree using json
[
{
"data" : {
"icon" : <optional>,
"title" : <node name>
},
"attr" : {
"rel" : <the type you defined in the js (maybe "group")>,
"title" : <node title>,
"id" : <the node's id / group id>
},
"state" : "closed"
}
]
I would recommend that you use the output from json_encode as it is. Takes less bandwidth. Only reason I see for all the whitespace is for debugging, and for that I'd rather use FireBug and/or JSONView in FireFox.
Anyways, if you really want to, you can maybe try the JSON_PRETTY_PRINT flag? Seems this was added in 5.4.0 though, so maybe not the version you're on supports it... There seems to be options you can use for that in the comments there though. Maybe you can find something useful? http://www.php.net/manual/en/function.json-encode.php#102091
You say you have to create a jstree now, and that doesn't really have anything to do with what you're asking. You're two examples of data doesn't look anything alike at all. json_encode does not do anything special or magic. It just takes data and turns it into JSON. It's your job to make that data look correctly first, before encoding it. Your DB query most likely returns a set of flat rows, and you'll have to loop through it and somehow generate your tree the way you want it. You can probably find other questions here about how to create tree structures out of flat DB results.
Since you are using Zend Framework, I recommend you to use Zend_Json. Zend_Json is a pretty useful component to use in order to format Json from any supported format (object, array, xml...).
Zend_Json::decode() and Zend_Json::encode() will allow you to encode and decode Json and prettyPrint() is used to make your output prettier.
Edit:
As Svish said, your two examples doesn't look alike, so it's kind of hard to guess what you want to put inside your tree.
What you need is to create your own array, so you can make it look like the way you want.
For example, let's say you only want one row from your database in your tree, then your array would be something like this:
$v = array(
array(
"data" => array("icon" => "ICON",
"title" => $row->name),
"attr" => array("rel" => "REL",
"title" => "TITLE",
"id" => $row->group_id),
"state" => "closed"));
echo Zend_Json::encode($v);
These lines should echo something like in your examples.
To make it works with your fetchAll(), a simple foreach will do it.
Here is a template of a possible text file I might need to import into my database:
#NAME:"Test"
#REV:"rev1"
#PRODUCT:"product1","description1","option1"
#PRODUCT:"product2","description2","option1","option2"
"A1","key1","DALI"
"B1","key2",""
"B2","key3","option2"
"C1","key4",""
The first 4 lines is a new addition to the format of these files. I was importing the comma separated data itself successfully before the addition of the comment lines on top.
I was wondering if someone can provide me the most efficient way to put all the values in the comment lines into variables in PHP.
I always have a little trouble when it comes to RegEx. I'm not sure how to best grab the lines starting with a #.
Essentially, I would like to have the following data available to me:
$csv['name']: "Test";
$csv['rev']: "rev1";
$csv['products']: array(
0 => array('name' => "product1", 'desc' => "description1", 'options' => "option1"),
1 => array('name' => "product2", 'desc' => "description2", 'options' => "option1,option2"),
);
$csv['data']: The rest of the data in text file
There could be multiple #PRODUCTS defined, so that is why it would be nice to have an array made from those lines.
Thanks for your help.
Are you using php 5.3? If so, then you can simply read your file using fgets() and detect comments using substr($line, 0, 1). If you don't detect a #,it means it a data line, then pass it on to str_getcsv()...
Cheers
To match something started with #, just use ^ at the beginning of regexp (outside of group)