PHP Use regex to find and remove a variable in a string - php

With PHP, I'm opening a file and it looks like this:
var people = {
vikram: { time1: [ '8:00am', '8:20am', '8:40am', '9:00am', ], time2: [ '10:20am', '10:40am', '11:00am', '11:20am', ], time3: [ '8:00am', '8:20am', '8:40am', ], }};
The variable I'm trying to remove will contain a time (ex. 8:00am) and I will know the timeIndex(ex. time1). I also want to keep all the other times intact.
For example, if I set the variable to 8:40am, I want the new file that is being created to look like this:
var people = {
vikram: { time1: [ '8:00am', '8:20am', '9:00am', ], time2: [ '10:20am', '10:40am', '11:00am', '11:20am', ], time3: [ '8:00am', '8:20am', '8:40am', ], }};
Any help would be appreciated!

The format you show represents a JSON formatted string. You can use json_decode() function to make an array from string, then loop through the array and just unset() the element you don't need.

you can use preg_replace() for this:
<?php
$filename = 'yourfile.js';
$search = '8:40am';
$content = file_get_contents( $filename );
$pattern = '/(\s*time1:\s*\[.*)([\'"]' .
preg_quote($search) .
'[\'"],?\s*)(.*\])/U';
$content = preg_replace( $pattern, '\1\3', $content );
file_put_contents( $filename, $content );
?>
This is a modification of the code example i answered to your last question on a similar topic.

Here is the way I did it. Basically, I use json_decode to parse your json to php object. However, I also found that your input is not a well-formed json for php (See example 3). Although my code doesn't look good and generic, but I hope it will help you.
<?php
$json_data = '{
"vikram": {
"time1": ["8:00am", "8:20am", "8:40am", "9:00am"],
"time2": ["10:20am", "10:40am", "11:00am", "11:20am"],
"time3": ["8:00am", "8:20am", "8:40am"]
}
}';
$obj = json_decode($json_data);
//var_dump($obj->vikram);
$value = "8:40am";
$time1 = "time1";
$delete_item;
foreach($obj->vikram as $name=>$node)
{
foreach($node as $i => $time)
{
if($time==$value && $name=$time1)
{
$delete_item = $i;
}
}
}
unset($obj->vikram->time1[$delete_item]);
var_dump($obj->vikram);

Related

Get an array in a php file from http request

I'm learning php and I'm trying to get a php file from a http request using Guzzle and then just take a particular array from those contents and ignore the rest. But I'm unsure how to get that array.
<?php
require_once "vendor/autoload.php";
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET', 'http://api-address/file.php');
$body = $response->getBody();
$decoded = json_decode($body, true);
$contents = file_get_contents($decoded);
When I print $contents it looks as expected, for example:
<?php
$var = "example string";
$array = [
[
'name' => 'stuff I need'
]
];
I want to just get the array, iterate through it and write each to a file but I don't know how to get just that and ignore the other stuff that isn't in that array it if that makes sense. Any help would be appreciated.
You are using ...
json_decode($body, true);
That method converts the content to array, that means that probably if you do a ...
var_dump($decoded);
you can see an array that it contents arrays inside ...
Well, I mean, you can get ...
$array = [
[
'name' => 'stuff I need'
]
];
Navigating into $json_decode() array.
If you are asking the how, well, just use the next step ...
$contentArray = $decoded[1] //With this you can get the array that you need.

JSON to Array using PHP json_decode

I'm reading a json file using
$jsonStr = file_get_contents("connection.json");
$jsonParsed = json_decode($jsonStr,true);
and I want $jsonParsed to be a associative array like this:
$jsonParsed = { "SERVER" => "111.222.333.444" , "USER" => "edvaldo" , "PASSWORD" => "my_password_here", "DATABASE" => "my_database_here" };
What is the format of the JSON needed to do this?
I tried this
{
"SERVER": "111.222.333.444",
"USER": "edvaldo",
"PASSWORD": "my_password_here",
"DATABASE": "my_database_here"
}
but even with JSONLint saying this piece og JSON is valid, I can't get the result I need.
I'm not really very used to JSON and then I will appreciate a lot any help given.
EDITED:
This is the function I'm using:
private function set_mysql_parameters() {
$this->connectionParams = array();
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_mysql = file_get_contents($json_file);
$json_parsed = json_decode($json_file,true,250);
foreach($json_parsed as $key => $value) {
$this->connectionParams[$key] = $value;
}
}
My goal is to fill this array $this->connectionParams with data extracted from the JSON file.
I notice that you are trying to decode the filename instead of the content.
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_parsed = json_decode($json_file,true,250);
Shouldn't it be
$json_parsed = json_decode($json_mysql, true, 250);

How could I reorganize json arrays and give key string to each key while arraying them into arrays within an array through php?

currently I use three separate php functions to array:
folder names
a thumbnail under the folder
a text file under the folder
into three separated json files, so they now are:
["folder1","folder2","folder3"]
["folder1/thumb.svg","folder2/thumb.svg","folder3/thumb.svg"]
["blah blah blah","blah blah blah","blah blah blah"]
This works fine for me but it would be so much easier if I can make them into one json file looks like this:
[
{
"name" : "folder1",
"thumbnail" : "folder1/thumb.svg",
"text": "blah blah blah"
},
{
"name" : "folder2",
"thumbnail" : "folder2/thumb.svg",
"text": "blah blah blah"
},
{
"name" : "folder3",
"thumbnail" : "folder3/thumb.svg",
"text": "blah blah blah"
},
]
Is there a way to do it? Thanks.
Explain more:
For example I tried array("name" => array_map("basename", glob('./folders/*', GLOB_ONLYDIR)),) and it just put all my folders as a giant array under one single entry of "name," like this {"name":["folder1","folder2","folder3"]}.
A pseudo solution:
IkoTikashi provided a solution, while not necessary answering the question, but could be useful to some people. I use his idea to establish some example codes below:
<?php
$checkfolder = './path/examples/folders';
$json = [];
foreach ( glob($checkfolder . '*', GLOB_ONLYDIR) as $folder)
{
$filename = $folder . "/description.txt";
if (file_exists($filename)) {
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
} else {
$contents = '';
}
$json[] = [
'name' => str_replace($checkfolder, '', $folder),
'thumb' => $folder . '/thumb.svg',
'text' => $contents
];
}
json_encode($json);
?>
Of course this solution isn't perfect. For one it doesn't provide usable url for thumbnails. And more importantly it erased the modularity of the original codes - that users can use three separated api to generate specific json to their need. The reason to reorganize the existing json files is that they can have an additional option to generate combined arrays. This solution, rather, created a whole new function to accomplish such goal - so while it is a temporary solution, it lacks of upgradability.
Read in all directories under folders/ and use them to set a new array:
<?php
$checkfolder = 'img/';
$json = [];
foreach ( glob($checkfolder . '*', GLOB_ONLYDIR) as $folder)
{
$folderName = str_replace($checkfolder, '', $folder);
$json[] = [
'name' => $folderName,
'thumbnail' => $folderName . '/thumb.svg',
'text' => 'blah blah blah'
];
}
print_r(json_encode($json));
Inside of that loop you would do file existance checks, reading the text etc.
json in general is a text, so, if you want to make your script a JSON data source, you are able to print it out in that format.
For example:
echo "{\n";
echo "{\n";
echo "'name':'$folderArr[0]'\n";
echo "}\n";
echo "}\n";
However, you must get sure that there's no any other text printout will be occurred on the script to avoid corruption of JSON format.

Return JSON inside data[] php

I'm using the following to pull some data fro facebook:
$tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token);
echo $tagData;
This produces e.g.:
{"data":
[
{"name":"Jonathan Montiel","id":"28125695"},
{"name":"Jackson C. Gomes","id":"51300292"}
],
"paging":{"next":"https:\/\/graph.facebook.com\/123456789\/friends?access_token=5148835fe&limit=5000&offset=5000&__after_id=100060104"}}
QUESTION How I can just return ONLY what's inside the [...] including the [ ]?
Desired result:
[
{"name":"Jonathan James","id":"28125695"},
{"name":"Jackson C. Cliveden","id":"51300292"}
]
Try this:
$tagData = json_decode( $tagData, true );
$data = $tagData['data'];
echo json_encode( $data );
This basically converts the JSON to an array, extracts the desired part and returns this again as JSON-encoded.
EDIT
Example Fiddle
json_decode and reencode with json_encode necessary part of the response. Following is going to work for you:
$tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token);
$tagData = json_decode($tagData);
echo json_encode($tagData->data);
Thanks to Sirco for the inspiration, this works although how its different to answer given I have no clue!
$tagData = json_decode(file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token), true );
$data = $tagData['data'];
echo json_encode( $data );

how to retrieve array value using php

I want to retrieve array value.
This is my array value:
overlay.txt:
{"title":"sss","description":"sss","code":"sss"}
{"title":"trtr","description":"trtr","code":"tyrytr"}
{"title":"ret54","description":"56tr","code":"ty76"}
{"title":"rgfdg","description":"dfgdfg","code":"dfgdfg"}
{"title":"asfafdsf","description":"sdfsdf","code":"sdfsdfsdf"}
This is my code: but this is not working.why?
How to retrieve value from overlay.txt file.
I did not get all title value.
I do not known how to get title value from overlay.txt
The $title is showing empty.
Where I want to change in my code to get $title value.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
$fd = fopen($file, "a"); // a for append, append text to file
fwrite($fd, $json);
fclose($fd);
$filecon = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays',$filecon);
//overlays page;
foreach($filecon as $files)
{
$title=$files['title'];
echo $title;
}
You're encoding your array to JSON, so at some point you need to decode it again into a PHP array. Since you actually have several JSON objects in the file, you need to decode each one individually. Assuming it's always one JSON object per line, this'll do:
$jsonObjects = file('overlay.txt', FILE_IGNORE_NEW_LINES);
foreach ($jsonObjects as $json) {
$array = json_decode($json, true);
echo $array['title'];
...
}
This will very quickly break if there are line breaks within the serialized JSON, e.g.:
{"title":"ret54","description":"foo
bar","code":"ty76"}
That way of storing the data is not very reliable.
make overlay.txt fully json format:
[
{"title":"sss","description":"sss","code":"sss"},
{"title":"trtr","description":"trtr","code":"tyrytr"},
...
]
and try this:
$raw = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays', array("filecon" => json_decode($raw)));
overlay page:
<?php
foreach($filecon as $files) {
echo $files['title'];
}
?>
If you want to use $filecon in view file,
set an array which has the key "filecon" in $this->load->view()'s second argument.
http://codeigniter.com/user_guide/general/views.html

Categories