0

The dump of the following array is:

$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
array(2) { [60]=> int(116) [50]=> int(117) } 

As shown above, the key is 60 and 50 (which is qcounter), while the value is 116 and 117 (which is id).

I'm trying to assign the qcounter to a variable as follows, but with a fixed index, such as 0,1,2,3 .. etc :

$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];

And the same with id :

$id1= $quest_all[0];
$id2= $quest_all[1];

Any help is appreciated.

1
  • Can you please elaborate on your question a bit more. What is the actual requirement? Commented Oct 15, 2019 at 17:01

3 Answers 3

1

Try as below: One way is: array_values($quest_all); will give you an array of all Ids array_keys($quest_all); will give an array of all qcounters and respective indexes for qcounter and ids will be the same.

Other way, First get all qcounters only from collection:

$quest_all = $qwinners->pluck('qcounter')->toArray();
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
    ...
    and so on

Then get all ids

$quest_all = $qwinners->pluck('id')->toArray();
$id1= $quest_all[0];
$id2= $quest_all[1];
    ...
and so on

You can also use foreach to iterate through the result array.

Sign up to request clarification or add additional context in comments.

Comments

0

To reset array keys, use array_values(). To get array keys, use array_keys():

$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
$quest_all_keys = array_keys($quest_all);
$quest_all_values = array_values($quest_all);

Or simply use foreach():

$keys = [];
$values = [];
foreach($quest_all as $key => $value){
    $keys[] = $key;
    $values[] = $value;
}

1 Comment

But array_values has replaced the qcounter. How can I still keep both "id" and "qcounter" in the array to then assign them to variables ?
0

I am not sure why you want variable names incrementing when you could have an array instead but if you don't mind an underscore, '_' in the name and them starting at 0 index you can use extract to create these variables. (As an exercise)

$quest_all = ...;

$count = extract(array_keys($quest_all), EXTRA_PREFIX_ALL, 'qcounter');
extract(array_values($quest_all), EXTRA_PREFIX_ALL, 'id');
// $qcounter_0 $qcounter_1
// $id_0 $id_1


for ($i = 0; $i < $count; $i++) {
    echo ${'qcounter_'. $i} .' is '. ${'id_'. $i} ."\n";
}

It would probably be easier to just have the 2 arrays:

$keys = array_keys($quest_all);
$values = array_values($quest_all);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.