Jan Willem
Jan Willem

Reputation: 35

How to create an array of every nth item?

Say I have the following table:

name
----
A
B
C
D
E
F
G
H
I

I can extract this from MySQL and put it in an array:

$result = mysql_query("SELECT * FROM names ORDER BY name DESC");
while ($row = mysql_fetch_object($result)) {
  $names[] = $row->name
}

What I am now looking for is a script that loops through $names and returns pairs, for instance every 3rd name:

array(
  [A] => [C],
  [B] => [D],
  [C] => [E],
  [D] => [F]
  [E] => [G]
  [F] => [H]
  [G] => [I]
)

Or, for instance, every 4th name:

array(
  [A] => [D],
  [B] => [E],
  [C] => [F],
  [D] => [G]
  [E] => [H]
  [F] => [I]
)

The number of names in between (3 in the fist example, 4 in the second) should be variable. Does anybody know how to do this in php?

Upvotes: 0

Views: 2166

Answers (3)

salathe
salathe

Reputation: 51950

Another option is to use the array_slice() and array_combine() functions to create the key/value pairs that you are wanting.

function array_nth(array $array, $nth)
{
    $keys   = array_slice($array, 0, -($nth - 1));
    $values = array_slice($array, $nth - 1);
    return array_combine($keys, $values);
}

For example,

$names = range('A', 'I');
var_export(array_nth($names, 3));

Gives

array (
  'A' => 'C',
  'B' => 'D',
  'C' => 'E',
  'D' => 'F',
  'E' => 'G',
  'F' => 'H',
  'G' => 'I',
)

Upvotes: 1

Raekye
Raekye

Reputation: 5131

I'm assuming these are indexed (by number)? Since in your example you just list [a, b, c]. Something like (might have an off by one bug but this is the idea):

function pairs($arr, $offset) {
    $rv = array();
    for ($i = 0; $i < (sizeof($arr) - $offset); $i++) {
        $rv[$arr[$i]] = $arr[$i + $offset];
    }
    return $rv;
}

Think it's pretty self explanatory. (sizeof($arr) - $offset) just makes sure you don't go off the end whne you have the $arr[$i + $offset];

Upvotes: 0

Ayush
Ayush

Reputation: 42450

You can do this using a fairly simple for loop.

Here's an example. All you need to do is tweak $seperation:

<?php

$array = array('A','B','C','D','E','F','G','H','I');
$seperation = 3;
$assoc = array(); // stores result

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

print_r($assoc);

Demo

Upvotes: 1

Related Questions