【问题标题】:skip first value for variable inside of foreach loop php跳过foreach循环php中变量的第一个值
【发布时间】:2019-02-16 01:47:12
【问题描述】:

我的网站上有以下函数,它从$vid_pix 中获取所有值,并echo 每个它们或foreach 循环中的任何相关变量。

这很好用,但是我有一个变量 - $Pt,它也会回显

虽然我现在要做的是 - 跳过$Pt 中的第一个值。还要为最后一个实例设置一个静态值,因为所有内容都向上移动 1,最后一个实例没有任何值。

我试过array_spliceunset,但它没有跳过第一个$Pt 值。

如果我有 -

[vp 1]->[5]
[vp 2]->[10]
[vp 3]->[15]
[vp 4]->[20]

我需要 -

[vp 1]->[10]
[vp 2]->[15]
[vp 3]->[20]
[vp 4]->[x]

(x = 我必须为最后一个变量分配一个静态值。)

我的功能(为简单起见,已精简)

$vid_pix = get_post_meta($v_Id, 'vid_pix', false);

foreach ($vid_pix as $vP) {
    $Pt = get_post_meta($vP, 'photo_time', false);
    array_splice($Pt, 0, 1);
    //unset($Pt[0]);
    $Pt = get_post_meta($vP, 'photo_time', true);
    echo $Pt;

    if (last -> $Pt) { // something like this for the last value
        $Pt = '5';
    }
 }

为了更好地理解,这里是我试图在其中实现的特定功能的完整代码--

/*
This is for looping through the uploaded pictures
and sorting them and creating a text file.
*/

$vid_pix = get_post_meta($v_Id, 'vid_pix', false);

$data = "ffconcat version 1.0";
$line = '';

        usort( $vid_pix, function( $a, $b ){
            $aPor = (int) get_post_meta( $a, 'photo_order', true );
            $bPor = (int) get_post_meta( $b, 'photo_order', true );

            if ( $aPor === $bPor ) {
                return 0;
            }

            return ( $aPor < $bPor ) ? -1 : 1;
        } );

        foreach ($vid_pix as $vP) {
$filename = basename( get_attached_file( $vP ));
$Pt = get_post_meta($vP, 'photo_time', true);
$Por = get_post_meta($vP, 'photo_order', true);

$static_value=25;
$array=$Pt;

reset($array);//reset the internal pointer
while(false!==($key=key($array))&&null!==key($array)){//check for current key validity
    $next=next($array);//get the next value and move the pointer
    $array[$key]=$next&&isset($array[$key])?$next:$static_value;//assign the next value to the current key  if valid or the static value if false 
}

var_dump($Por);
var_dump($array);

// try to determine the pic of the placeholder image

if ($vP === end($vid_pix))
        $last_img = $thepath.'/'.$filename;


if ($vstyle === 'Custom') { // if custom timing is chosen

$slide_dur = "\r\nduration ".$Pt;

$filename = basename( get_attached_file( $vP ));
$line .= "file '".$thepath."/".$filename."'".$slide_dur."\r\n";


} else { // if custom timing is NOT chosen

$filename = basename( get_attached_file( $vP ));
$line .= "file '".$thepath."/".$filename."'".$slide_dur."\r\n";

}

$total_items = count($vid_pix);

if ($total_items > 1) { // if total items is more than one

// LAST LINE OF CONCAT TEXT FILE
$lastline = "file '".$last_img."'\r\nduration 2\r\nfile '".$last_img."'";

$isitone = "";
$solopic = "";


// PUT TOGETHER ALL THE LINES FOR THE TEXT FILE
$txtc = $data."\r\n".$line.$lastline;

} else { // if total items is less than one

$isitone = "true";
$solopic = "-loop 1 -probesize 10M -i ".$thepath."/".$filename;

}
}

// SAVE THE TEXT FILE
file_put_contents($thepath.'/paths.txt', $txtc);

更新

var_dump 结果-

string(1) "7"
string(1) "2"
string(1) "6"
string(1) "9"

以下链接包含保存$Pt变量的原始代码——here

【问题讨论】:

  • array_shift() 怎么样?
  • 或者不要丢弃它,而是使用 for 循环,将数组从第二个元素迭代到最后一个元素。
  • @dnFer 因为那样我将不得不改变其他的事情,所以我尽量保持简单。
  • 您的示例与您的解释不符。您的示例暗示您要跳过第一个元素vp 1,但您的解释表明get_post_meta 的输出不是您想要的。请澄清。
  • 不跳过$Vp的第一个元素,跳过第一个$Pt。 $Vp 是一个 ID 号,$Pt 是在与该 ID 关联的表单中输入的数字值。所以我希望 ID # 1 具有来自 ID # 2 的 $Pt 值......现在有意义吗? @DevDonkey

标签: php arrays wordpress foreach key-value


【解决方案1】:

基于OP's comments$Pt 是一个数组数组。所以我们只需使用array_shift 来删除第一个值(第二级数组)。并且,在末尾追加一个静态值数组:

$vid_pix = get_post_meta($v_Id, 'vid_pix', false);

foreach ($vid_pix as $vP) {
    $Pt = get_post_meta($vP, 'photo_time', false);

    // $Pt is an array of array
    // remove the first key (first array)
    $first_key = array_shift($Pt);

    // Add the static value to end of the array. eg: '5'
    $static_value = '5'; // define static value
    $Pt[] = array($static_value);

    // print them out
    var_dump($Pt);
}

【讨论】:

  • @Rich 除非有更多的内联 cmets,否则非常不清楚您要通过整个代码实现什么。无论如何,根据您最初发布的要求,我相信我可以帮助您实现这一目标
  • @Rich 我已经更新了代码,与您的精简示例代码同步。请检查并告诉我!
  • 我试过你的代码,var dump 的输出是 -- array(1) { [0]=&gt; string(1) "5" } array(1) { [0]=&gt; string(1) "5" } array(1) { [0]=&gt; string(1) "5" } array(1) { [0]=&gt; string(1) "5" } array(1) { [0]=&gt; string(1) "5" } 但我的实际值是 - 7, 2, 6, 9, blank
  • @Rich $Pt 的 var_dump 的输出也是什么?
  • 它是——array(1) { [0]=&gt; string(1) "7" } array(1) { [0]=&gt; string(1) "2" } array(1) { [0]=&gt; string(1) "6" } array(1) { [0]=&gt; string(1) "9" } array(1) { [0]=&gt; string(0) "" }
【解决方案2】:

为什么不用最简单的方法呢?

$keys = array_keys($myHashArray);
$values = array_values($myHashArray);
array_shift($keys);
array_shift($values);
$result = array_combine($keys, $values);

如果我理解错了,请纠正我。

【讨论】:

  • 他想跳过get_post_meta的第一个值,而不是父数组。我和你一样读了。这个问题模棱两可。另外,为什么要进行2次检查?为什么不if(!$isFirst)
  • 谢谢,我已经改了答案
【解决方案3】:

你可以像这样简单地继续:

$static_value=25;
$array=['vp 1'=>5,'vp 2'=>10,'vp 3'=>15,'vp 4'=>20];

reset($array);//reset the internal pointer
while(false!==($key=key($array))&&null!==key($array)){//check for current key validity
    $next=next($array);//get the next value and move the pointer
    $array[$key]=$next&&isset($array[$key])?$next:$static_value;//assign the next value to the current key  if valid or the static value if false 
}


var_dump($array);

输出:

array(4) {
  ["vp 1"]=>
  int(10)
  ["vp 2"]=>
  int(15)
  ["vp 3"]=>
  int(20)
  ["vp 4"]=>
  int(25)
}

【讨论】:

  • 我已经用我的完整代码和你的建议更新了我的问题,但它没有改变任何东西。
  • @Rich 我真的不明白你想用这段代码实现什么,但是你没有按预期使用我的代码。要么你用 $Pt 替换所有出现的 $array或者你使用$array=&amp;$Pt 而不是简单的$array=$Pt。此外,如果 $Pt 是一个数组,你为什么要尝试将它连接到代码中的字符串?
【解决方案4】:

怎么样?

$new_array = array_combine( // to make an array from $keys / values
  array_keys($old_array), // use the old same keys
  array_merge( // the array containing your new values
    array_splice($old_array, 1), // remove the first element
    [$static_value] // add the static value
  )
);

在此处实时查看:https://repl.it/repls/PerfectUpsetAnalysts

【讨论】:

    【解决方案5】:
    $vid_pix = get_post_meta($v_Id, 'vid_pix', false);
    $i = 0;
    foreach ($vid_pix as $vP) {
       if($i ==0){
    continue;
    }
        $Pt = get_post_meta($vP, 'photo_time', false);
        array_splice($Pt, 0, 1);
        //unset($Pt[0]);
        $Pt = get_post_meta($vP, 'photo_time', true);
        echo $Pt;
    
        if (last -> $Pt) { // something like this for the last value
            $Pt = '5';
        }
    $i++;
     }
    

    使用这种类型的计数器来跳过值....

    【讨论】:

      【解决方案6】:

      正如您已经知道的那样,您将获得每个 vid_pixphoto_time 并且在您的问题中,我看到您需要为当前的vid_pix 获得下一个 vid_pixphoto_time 并忽略第一个 photo_time 这是5 在提供的示例和最后一个 vid_pix (改为静态)

      [vp 1]->[5]
      [vp 2]->[10]
      ...
      

      我需要 -

      [vp 1]->[10]
      [vp 2]->[15]
      ...
      

      所以我认为它很简单(我使用vip_pix index 作为键,你可以使用任何东西)

      $pt_result = [];
      for ($i = 0; $i < count($vid_pix) - 1; ++$i) {
          $pt_result[$vid_pix[$i]] = get_post_meta($vid_pix[$i+1], 'photo_time', true);
      }
      $pt_result[$vid_pix[$i]] = 25; //set last one statically
      

      【讨论】:

      • 我将如何将它与我当前的代码一起使用? $pt_result 将取代 $Pt?
      • @Rich pt_result 是一个数组,将 vip_pix ID 作为键,将 poto_time 作为值。你可以用你想要的方式改变它。在第一个代码中,您只需回显 pt。所以你也可以在循环中回显 $pt_result 数组。在第二个代码中,您将其推送到一个数组中。 $pt_result 已经是一个 pt 数组
      【解决方案7】:

      您需要将数组移出循环,因为您的 $Pt 数组只有一个值。试试下面给出的代码。

      $newPt = array(); // initialize new array
      $vid_pix = get_post_meta($v_Id, 'vid_pix', false);
      
      foreach ($vid_pix as $vP) {
          $Pt = get_post_meta($vP, 'photo_time', false);
      
          // assign to new array
          $newPt[] = $Pt;
      }
      
      // remove first value
      array_shift( $newPt );
      
      // add static value to end of the array
      $static = '5';
      $newPt[] = array( $static );
      
      // print updated array
      var_dump($newPt);
      

      希望这会有所帮助。

      【讨论】:

      • 我不明白你的答案,以及我想如何在我的代码中使用它。
      • photo_time 元数据是否有多个值或单个(对于每个vid_pix 元数据)?
      • 你是说你的数组有值7, 2, 6, 9, blank,无论是它的单个$Pt值还是$vid_pix循环之后?
      • $Pt 值附加到 $vid_pix。所以它是一个数组的数组
      • 好的,我知道它是数组数组,但你能在foreach ($vid_pix as $vP) 循环中使用var_dump($Pt); die(); 确认第一个循环 输出吗?
      【解决方案8】:

      如何将get_post_meta($vP, 'photo_time', false); 的结果传递给一个函数,该函数会移动值并将静态值添加到末尾?

      function shiftPt($input, $end = null) {
          $output = [];
          $prevKey = null;
          foreach ($input as $key => $value) {
              if ($lastKey) $output[$lastKey] = $value;
              $lastKey = $key;
          }
          $output[$key] = $end;
          return $output;
      }
      

      所以基本上你可以像这样包装你现有的函数......

      $pT = shiftPt(get_post_meta($vP, 'photo_time', false));
      

      ...这会将数组中的最后一个值保留为空,同时将所有原始值向上移动。

      如果您想指定最终值(例如 5),那么您可以这样做...

      $pT = shiftPt(get_post_meta($vP, 'photo_time', false), 5);
      

      【讨论】:

      • 如果 $Pt 是附加到 $vid_pix 数组的数组,这将起作用。
      • 它会 - 尽管基于您上面的示例代码 $Pt 没有“附加”到 $vid_pix 数组。在您的代码中,$Pt 是一个变量,由 get_post_meta($vP, 'photo_time', false) 的结果创建和填充 - $vid_pix 无关紧要。
      • 在我的更新中,我添加了一个指向更多代码的链接,以显示 $Pt 与 $vid_pix 的相关性
      【解决方案9】:

      更新 #1

      尝试像这样使用array_shift()

      foreach ($vid_pix as $vP) {
          $Pt2 = get_post_meta($vP, 'photo_time', false);
          $Pt = array_shift( $Pt2 ); // get first value
          $Pt2[] = 'static value';
          var_dump( $Pt, $Pt2 ); // test
      }
      

      更新 #2

      如果每个图像/附件实际上只有 一个 photo_time 元(附件 ID 在 $vid_pix 数组中),那么这应该可以:

      $Pt2 = [];
      $n = count( $vid_pix );
      for ( $i = 0, $j = 1; $i < $n; $i++, $j++ ) {
          $Pt2[] = ( $n === $j ) ? 'static value' :
              get_post_meta( $vid_pix[ $j ], 'photo_time', true );
      }
      echo implode( ', ', $Pt2 ); // test
      

      更新 #3

      添加上面的($Pt2)代码上面/在这个foreach之前,然后添加$i =&gt;,并更改$Pt,如下所示:

      foreach ($vid_pix as $i => $vP) {
        $filename = basename( get_attached_file( $vP ));
        $Pt = $Pt2[ $i ];
        ...
      }
      

      【讨论】:

      • 我的输出看起来像这样 -- 5491: static value&lt;br&gt;5492: static value&lt;br&gt;5493: static value&lt;br&gt;5494: static value&lt;br&gt;5495: static value
      • 我的输出看起来像这样 - string(2) "10" array(1) { [0]=&gt; string(12) "static value" } string(1) "7" array(1) { [0]=&gt; string(12) "static value" } string(1) "5" array(1) { [0]=&gt; string(12) "static value" } 我在这个例子中使用的数字是 '10,7,5'
      • 所以$Pt2[10, 7, 5]$vid_pix 怎么样?它们的实际值是多少?
      • 你期望的输出是什么?
      • 不客气@Rich。但也许我应该补充一点,您不再需要 $array 就像当前问题的代码中那样。 (因为$Pt2 代码已经在做同样的工作了。)
      【解决方案10】:

      您可以使用 array_slice 从数组中删除一组值,并使用 array_merge 将其与“x”合并。

      然后你只需组合键和“新”值。

      $arr = [
      'vp 1'=>[5],
      'vp 2'=>[10],
      'vp 3'=>[15],
      'vp 4'=>[20]];
      
      $keys = array_keys($arr);
      $values = array_merge(array_slice($arr, 1), ["x"]);
      
      $new = array_combine($keys, $values);
      var_dump($new);
      

      这个输出:

      array(4) {
        ["vp 1"]=>
        array(1) {
          [0]=>
          int(10)
        }
        ["vp 2"]=>
        array(1) {
          [0]=>
          int(15)
        }
        ["vp 3"]=>
        array(1) {
          [0]=>
          int(20)
        }
        ["vp 4"]=>
        string(1) "x"
      }
      

      https://3v4l.org/l7NBa

      【讨论】:

      • 是的。我做了$arr = $Pt,这是输出array(1) { [0]=&gt; string(1) "x" } array(1) { [0]=&gt; string(1) "x" } array(1) { [0]=&gt; string(1) "x" }
      • 在这种情况下,您的问题不会显示您得到了什么。我使用了您问题中的数组并获得了您想要的输出,如您在链接中看到的那样。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      相关资源
      最近更新 更多