【问题标题】:Edit and complete string with foreach使用 foreach 编辑和完成字符串
【发布时间】:2018-06-12 08:10:11
【问题描述】:

如何在每个循环中完成我的变量?

$string = "Our products are shoes, pants, shirts."
$products = get_post_meta( post_id, 'products', true );
$matches = get_post_meta( post_id, 'matches', true );

$newPhrase = '';

foreach ($matches as $match){
    $id = searchForId($match, $products); // searching for the right id
    $newPhrase = str_replace($match, $products[$id]['sku'], $string);
}

// $newPhrase should be "Our Products are 3, 4, 9."

虽然每次 foreach 都会更改变量,但它总是会重新开始并采用旧字符串。例如:“我们的产品是鞋子,裤子,9。”

【问题讨论】:

    标签: php wordpress foreach


    【解决方案1】:

    您在这里遇到的问题是您将字符串重新保存回同一个变量。相反,您将其保存到$newPhrase。

    所以当循环再次运行时,它会再次调整旧的 unchanged 字符串,然后将其保存为 $newPhrase 变量 - 覆盖您在上一次循环迭代中所做的事情。这就是为什么您最终只更改了最后一个变量。

    不是每次都抓取旧的字符串,而是抓取调整后的字符串,像这样:

    $string = "Our products are shoes, pants, shirts."
    $products = get_post_meta( post_id, 'products', true );
    $matches = get_post_meta( post_id, 'matches', true );
    
    $newPhrase = $string;
    
    foreach ($matches as $match){
        $id = searchForId($match, $products); // searching for the right id
        $newPhrase = str_replace($match, $products[$id]['sku'], $newPhrase);
    }
    

    Here's a working php fiddle(略有调整,因为我无权访问您的产品元数据)。

    【讨论】:

    • 谢谢。这很容易。 ;-)
    • 哈哈哈随时@desmeit这是最能逃避我们的小事:)
    猜你喜欢
    • 2021-12-29
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多