How to set a fixed key for an array?

Asked

Viewed 30 times

-1

How can I set a key for an array with multiple values?

The array lists all trackers (in which case there is no key defined);

$trackers = array(
    'udp://9.rarbg.to:2970',
    'udp://tracker.coppersurfer.tk:6969/announce',
    'udp://tracker.leechers-paradise.org:6969'
);

Resultado:
Array
    (
        [0] => udp://9.rarbg.to:2970
        [1] => udp://tracker.coppersurfer.tk:6969/announce
        [2] => udp://tracker.leechers-paradise.org:6969
    )

Resultado desejado:
Array
    (
        [0] => Array
            (
                [protocolo] => udp://9.rarbg.to:2970
            )
        [1] => Array
            (
                [protocolo] => udp://tracker.coppersurfer.tk:6969/announce
            )
        [2] => Array
            (
                [protocolo] => udp://tracker.leechers-paradise.org:6969
            )
    )

Obs.: before opening the question I already reviewed the internet and I found nothing that helps me.

1 answer

2


Simply iterate with a for or foreach and add to a new array, it’s the basics of the language:

$trackers = array(
    'udp://9.rarbg.to:2970',
    'udp://tracker.coppersurfer.tk:6969/announce',
    'udp://tracker.leechers-paradise.org:6969'
);

$newTracks = array();

foreach($tracks as $track) {
    $newTracks[] = array( 'protocolo' => $track );
}

Now, something a little more "advanced", but that is native to the language and good to learn, are the references, in the case of PHP we use the commercial E (&), so no need to create a new array, just reference the EACH ITEM value of the foreach that will update the current array, thus:

$trackers = array(
    'udp://9.rarbg.to:2970',
    'udp://tracker.coppersurfer.tk:6969/announce',
    'udp://tracker.leechers-paradise.org:6969'
);

foreach($tracks as &$track) {
    $track = array( 'protocolo' => $track );
}

Of course if you are using a is normal or need references, because you will already have the INDEX VALUE, so:

$trackers = array(
    'udp://9.rarbg.to:2970',
    'udp://tracker.coppersurfer.tk:6969/announce',
    'udp://tracker.leechers-paradise.org:6969'
);

for ($i = 0; $i < count($tracks); ++$i) {
    $tracks[$i] = array( 'protocolo' => $track );
}

Thus $tracks[$i] you take the current Dice item and so on $tracks[$i] = you update it

  • Something so simple and I looking for a sophisticated method to do this, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.