提问者:小点点

移动或移位php数组键


不太确定如何正确地表达,但我正在寻找一些帮助来移动/移位数组键,以便顶层数组不包含另一个只有一个项目的数组。 基本上是从这里来的:

[0] => Array
    (
        [0] => Array
            (
                [_id] => 3
                [title] => Award winning wedding venue
                [subtitle] => Creating a website to reflect the prestige of the brand
            )

    )

[1] => Array
    (
        [0] => Array
            (
                [_id] => 5
                [title] => Bringing storytelling to life
                [subtitle] => Bringing storytelling to life
            )

    )

要像这样:

[0] => Array
    (
        [_id] => 3
        [title] => Award winning wedding venue
        [subtitle] => Creating a website to reflect the prestige of the brand
    )

[1] => Array
    (
        [_id] => 5
        [title] => Bringing storytelling to life
        [subtitle] => Bringing storytelling to life
    )

几乎只是把数组键上移一个。

原始数组使用以下方法创建:

// Start with manual relation otherwise default to next/prev    
    foreach ($item['related'] as $id) {
      
      $related[] = perch_collection('Projects', [
        'filter' => [
          [
            'filter' => '_id',
            'match'  => 'eq',
            'value'  => $id,
          ],
            // Item is enabled
          [
            'filter' => 'status',
            'match' => 'eq',
            'value' => 'enabled',
          ],
        ],
        'skip-template' => true,
      ], true);
    }

共2个答案

匿名用户

最好是修改数组的创建,而不是事后更改它。

// Start with manual relation otherwise default to next/prev    
foreach ($item['related'] as $id) {
  
    $related[] = perch_collection('Projects', [
        'filter' => [
            [
                'filter' => '_id',
                'match'  => 'eq',
                'value'  => $id,
            ],
            // Item is enabled
            [
                'filter' => 'status',
                'match' => 'eq',
                'value' => 'enabled',
            ],
        ],
        'skip-template' => true,
  ], true)[0];
}

注意perch_collection()函数调用末尾的[0]。 这与我回答的第二部分本质上是一样的,只是发生在较早的地方。

尽管如此,如果在生成原始数组后仍想更改它,则可以使用一个简单的foreach循环并引用原始数组。

foreach($array as &$arr) {
    $arr = $arr[0];
}

$arr前面使用&引用。 这意味着循环将改变原始数组,因此它可以防止临时数组的开销。

匿名用户

解决这个问题的最好方法是从源头入手。 这看起来像是从数据库接收到的数据集,因此在接收到数组之后,您可以尝试以正确的格式生成它,而不是尝试操作它。 大多数DAL都有方法来操作ResultSet的返回类型。

但是,如果这是不可能的,并且始终只有一个元素嵌套,那么这个循环应该可以解决这个问题。

for($i = 0; $i <= count($array); $i++) {
    $shifted[$i] = $array[$i][0];
}