如何将foreach结果存储在变量中并在数组中使用它

时间:2017-08-26 13:03:07

标签: php arrays loops variables foreach

我似乎无法弄清楚这一点。如何将foreach结果存储在变量中?这是我的代码。

$ids = get_field('auction_catalog');

if($ids) {
    foreach($ids as $id => $auctionids) {
        $string .= $auctionids . ', ';
    }

    echo $string;
}

上面的结果是:1,2,

但我想得到的结果是:'1', '2'

我想在数组中使用结果......

array(
    'taxonomy'=> 'auction-catalog',
    'field' => 'term_id',
    'terms' => array( $string ) // array('1', '2')
)

提前致谢!

4 个答案:

答案 0 :(得分:0)

您当前将其指定为单个字符串,而不是数组的元素。这意味着您在数组中使用字符串1, 2,获得一个元素。您可以explode()将字符串转换为数组中的元素,但是从头开始使用数组会更容易。

如果您希望生成的数组是包含$auctionids元素的数组,只需将它们添加到您提供给最终数组的数组中,就这样

$ids = get_field('auction_catalog');
$terms = array(); // Define the array

if($ids) {
    foreach($ids as $id => $auctionids) {
        $terms[] = $auctionids;
    }
}

$term现在是一个数组,你可以直接放在你的其他数组中,就这样

array(
    'taxonomy'=> 'auction-catalog',
    'field' => 'term_id',
    'terms' => $terms
)

答案 1 :(得分:0)

否则

$string = "1, 2";
$array = array($string);

将为您提供一个数组,其中包含一个1, 2元素。如果你想要一个数组,建立一个数组:

if($ids) {
    $idsArray = [];
    foreach($ids as $id => $auctionids) {
        $idsArray[] = $auctionids;
    }
}

现在$idsArray是一个包含所有$auctionids元素的数组。现在,您可以在terms

中使用它
array(
    'taxonomy'=> 'auction-catalog',
    'field' => 'term_id',
    'terms' => $idsArray
)

答案 2 :(得分:0)

假设$ids已经是一个数组,而您感兴趣的只是它的值,您可以使用array_values() - 不需要循环遍历数组:

$terms = array_values($ids);

供参考,见:

答案 3 :(得分:0)

使用爆破,如果要将字符串转换为数组,请使用爆炸

$array_to_string = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
$string_to_array= "a,b,c,d,e,f,g";

echo implode(',',$array_to_string ); // a,b,c,d,e,f,g


echo explode(',',$string_to_array); // ['a', 'b', 'c', 'd', 'e', 'f', 'g']