phpsqlfat-free-framework

replace all strings that contains a word in a PHP Array


I'm trying to all URLs that contain http://api.example.com/data/ to https://example.com/data/ in an array from a Database while using the Fat-Free Framework, the code iv tried below gives me

Internal Server Error, Array to string conversion

$f3->route('GET /details/@itemid',
    function($f3) {


$arr = array('result' => $f3->get('DBh')->exec('SELECT * FROM DB_table WHERE id=?',$f3->get('PARAMS.itemid')));

str_replace('http://api.example.com/data/', 'https://example.com/data/', $arr);

$f3->mset($arr);

        echo \Template::instance()->render('views/details.html');
    }
);

Solution

  • Well you've got a couple simple options to help with this. I'm also going to assume you mean to reference $arr['result'] and not just $arr and I'd need to assume you're only looking for one column out of the db column. I'll call this column url.

    Option 1

    foreach($arr['result'] as $key => $value) {
        if(empty($value['url'])) {
            continue;
        }
        $arr['result'][$key]['url'] = str_replace('http://api.example.com/data/', 'https://example.com/data/', $value['url']);
    }
    

    Option 2

    foreach($arr['result'] as &$value) {
        if(empty($value['url'])) {
            continue;
        }
        $value['url'] = str_replace('http://api.example.com/data/', 'https://example.com/data/', $value['url']);
    }
    

    Option 3

    $arr['result'] = array_map(function($value) {
        $value['url'] = str_replace('http://api.example.com/data/', 'https://example.com/data/', $value['url']);
        return $value;
    }, $arr['result']);
    

    My personal preference for readability and simplicity is Option 2. I believe foreach statements have been optimized to actually run faster than array_map which is......interesting.