0

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!

0

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

actually that is not valid JSON and can not be easily transformed to valid JSON.
0

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.

3 Comments

what about hello there {$username}!
for variables inside a double quote, you can enclose them in braces right.
@JackSpairow and how is that related to this question/answer?
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.