dongxiong1935 2016-03-08 10:26 采纳率: 0%
浏览 76
已采纳

从图像路径获取文件名(来自函数)

I am trying to get a file name from an image path using basename and echo it inside the title tag but I can't get it to work since I am echoeing the image path from a functions file.

What I am trying to do now (in product.php):

$path = ProductBekijkPlaatje($contenti[0]['images']);

$basename = basename($path);

echo $basename;

But this breaks the function and only echoes the filepath, while the actual image is lost.

This is the function I am calling (in functions.php):

function ProductBekijkPlaatje($plaatje) {

    $path = $img->image_intro;

    $basename = basename($path);

    $img = json_decode($plaatje);

    if ($img->image_intro == '') {
        $image = '<img src="images/no-img.jpg" alt="">';
    } else {

        $image = '<img class="shorterimageimg" title="'.$basename.'" src="cms/'.$img->image_intro.'" alt="'.$img->image_intro_alt.'" >';

    }
    return $image;

}

I also try to show the image name in the title inside the function, but this isn't working either. What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • dpcj32769 2016-03-08 10:39
    关注

    it doesn't work in your function because you try to access the property of the object before you do json_decode():

    $path = $img->image_intro;     // $img doesn't exist here
    $basename = basename($path);
    $img = json_decode($plaatje);  // here $img is created
    

    Just move the json_decode() to the front:

    $img = json_decode($plaatje);
    $path = $img->image_intro;
    $basename = basename($path);
    

    Now, you could modify your function to return an array with different information:

    function ProductBekijkPlaatje($plaatje) {
        $img = json_decode($plaatje);
        $return = array();
        $return['path'] = $img->image_intro;
        $return['basename'] = basename($return['path']);
        if ($img->image_intro == '') {
            $return['image'] = '<img src="images/no-img.jpg" alt="">';
        } else {
            $return['image'] = '<img class="shorterimageimg" title="'.$return['basename'].'" src="cms/'.$img->image_intro.'" alt="'.$img->image_intro_alt.'" >';
        }
        return $return;
    }
    

    Then you can use this array later:

    $image = ProductBekijkPlaatje($contenti[0]['images']);
    echo $image['image']; // contains the html output
    echo $image['basename']; // contains the basename only
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器