extract random, non-overlapping values from PHP arrays

Asked 2 years ago, Updated 2 years ago, 74 views

I am having trouble because I can't realize how to extract values without randomly duplicating them from the array.
Here is the code.
When you actually run it, it says ArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArray.
Where is the cause?

//Create a card
$cards = array();
$marks = array("clover", "heart", "diamond", "spade");

for($mark=0;$mark<4;$mark++){
    for($num=1;$num<=13;$num++){
        $newCard=array($marks[$mark]=>"$num");
        array_push($cards,$newCard);
    }
}   

for($i=0;$i<=5;$i++){
    $land = array_land($cards, 2);
    echo$cards [$land[0]];
}

php array

2022-09-29 21:48

1 Answers

array_push is an array with a value added to the end of the array, so

array_push($cards,array('clover'=>10);

This is

array(
    0 = > 
    array(
        'clover' = > 10,
    ),
)

It will be shaped like this.
In other words,

echo$cards[0]

Even if

array('clover'=>10)

answers and the echo result is Array.

If I were to write,

echo'Mark:'.key($cards[$land[0]]).'Num:'.current($cards[$land[0]]]);

Also, I think you should take the key and the value of the array that you took out.

That's all about ArrayArrayArray.

Also, it seems that the card is being pulled in the second for statement, but since array_rand is used in the for statement, I don't think my wish to obtain it without duplication has been fulfilled.
If you want to retrieve it randomly using array_rand, use the second for statement

foreach(array_land($cards,6)as$cardKey){
    echo'Mark:'.key($cards[$cardKey]).'Num:'.current($cards[$cardKey]).PHP_EOL;
}

Why don't you make it look like this?


2022-09-29 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.