dougaxing8673 2014-11-30 19:22
浏览 49

php需要在数组顶部移动一个元素

Have array like this

Array
(
[] => 
[3837920201e05ba7c2fbffd3f1255129] => 'bg img a href Main | Delete etc'
[94ae40ff9b6df5bb123fb12211f48b11] => 'bg img a href Main | Delete etc'
[3974b3863e7ca7b7ea2026e44bbacfd2] => 'bg img a href Main | Delete etc'
)

Want to move key 3974b3863e7ca7b7ea2026e44bbacfd2 at top so array would look like

Array
(
[] => 
[3974b3863e7ca7b7ea2026e44bbacfd2] => 'bg img a href Main | Delete etc'
[3837920201e05ba7c2fbffd3f1255129] => 'bg img a href Main | Delete etc'
[94ae40ff9b6df5bb123fb12211f48b11] => 'bg img a href Main | Delete etc'
)

At first extract item that i want to be at top

$top_image = array_slice( $array, 2, 1 ); 

3974b3863e7ca7b7ea2026e44bbacfd2 is third element (as if key) in array (0,1,2)

Next want to create array $other_images. Decided to remove the initial third element and then merge both arrays.

Trying to remove third element. Read [array_splice][1] understand that first number (offset) is where i want to start to remove and second (length) - how many elements want to remove. So I tried

$top_image = array_splice( $array, 2, 1 ); 

But result is the same as with array_slice.

Then tried

foreach( $arr as $k => $val ){
   if( $k != 2 ){
      $other_images[] = $val;
   }
}

Expect to see 2 remaining elements. But see all 3.

What is wrong? How to remove certain element from array?

Regarding foreach $k can not be equal to 2, because $k is the long string... Tried for, but also not suitable...

  • 写回答

2条回答 默认 最新

  • doucha7329 2014-11-30 19:37
    关注

    Last elem ( 3974b3863e7ca7b7ea2026e44bbacfd2 => 'bg img a href Main | Delete etc' ) to top:

      // last value to top
      $last = array_pop($arr); 
      array_unshift($arr,$last);
    

    Update

      // last couple(key-value) to top
      end($arr);     
      $last_key = key($arr);
      $last_value = array_pop($arr); 
      $arr = array($last_key=>$last_value) + $arr;
      var_dump($arr);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100