【问题标题】:Array reorders and replaces help. (keys and values to a new array)数组重新排序并替换帮助。 (新数组的键和值)
【发布时间】:2011-06-01 19:38:33
【问题描述】:

请在这种情况下帮助我。我有一个数组,我想做一个新数组,比如

array[0][id] = 1
array[0][parent_id] = null
array[0][order_id] = 1
array[1][id] = 2
array[1][parent_id] = null
array[1][order_id] = 2
etc.

我现在的数组是这样的:

Array
(
[list] => Array // if the (array's name = `list`) the array[#][parent_id] = null
    (
        [0] => 1 // the key of the array (`[0]` in this case) is the array[#][order_id]
        [1] => 2 // the value of the array (`2` in this case) is the array[#][id]
        [2] => 5
    )

[list_2] => Array // else the array[#][parent_id] = the number value after the _
    (
        [0] => 3
        [1] => 4
    )

[list_5] => Array
    (
        [0] => 6
    )
)

基于 Habax 脚本的一个很好的解决方案:

$new = array();
$n=0;
foreach($old as $key=>$item){
    for ($i = 1; $i <= count($item); $i++) {
        if($key=='list')$new[$n]['parent_id']=null;
        else {
          $tmp = explode('_', $key);
          $new[$n]['parent_id']=$tmp[1];
        }
        $new[$n]['order_id']=$i;
        $new[$n]['id']=$item[$i-1];
        $n++;
    }
}
}

很好地安排嵌套排序,例如:http://www.b-hind.eu/jquery/

【问题讨论】:

    标签: php nested key jquery-ui-sortable


    【解决方案1】:

    我不明白你的台词

    [0] => 1 // the key of the array (`[0]` in this case) is the array[#][order_id]
    

    我认为这是价值,而不是关键:

    $new = array();
    $n=0;
    foreach($old as $key=>$item){
      if($key=='list')$new[$n]['parent_id']=null;
      else {
        $tmp = explode('_', $key);
        $new[$n]['parent_id']=$tmp[1];
      }
      $new[$n]['order_id']=$item[0];
      $new[$n]['id']=$item[1];
      $n++;
    }
    

    【讨论】:

    • 我的意思是在这种情况下数组[#][order_id] = 0,是的:P
    • 有没有order_id不为0的情况?
    • 是的。在 list_N 中:[order_id] => id,例如:[0] => 3,[1] => 4。我需要数组中的所有元素,我在你的脚本中做了一些修改,它几乎很好。 :P
    猜你喜欢
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 2020-06-17
    相关资源
    最近更新 更多