0

I am having a difficult time creating an associated array and assigning a value to the key. I have two arrays (tech_pay and tech_scans) and I am doing a simple calculation using their values and I want to create a new array called tech_per_scan but I keep getting an array with the key automatically created starting at 0.

    $tech_per_scan = array();
    foreach($tech_pay as $key=>$value)
    {  
        $pay_per_scan = $tech_pay[$key]['tot_pay']/$tech_scans[$key]['scans'];//calculate the payment per scan 
        $tech_per_scan[] = array('id'=>$key,'pay_per_scan'=>$pay_per_scan); 
    }

3 Answers 3

1

This line $tech_per_scan[] = array('id'=>$key,'pay_per_scan'=>$pay_per_scan); will add an element to you array and it will start with 0 as its index, because you did not specify its key. Similar to array_push

It should be $tech_per_scan[$id]

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

3 Comments

Thank you. I have got it now. Your explanations helped perfectly!
One last question: How do you close a question on this site?
You need to accept an answer by clicking on the "v" thing or delet ethe question
1
$tech_per_scan[$id] = $pay_per_scan; 

1 Comment

No, that does not work. If I print_r it I don't get the id:Array ( [] => 0 )
0

you should set value for new array like this :

$tech_per_scan[$key] = $pay_per_scan ; 

Full code is :

    $tech_per_scan = array();
    foreach($tech_pay as $key=>$value)
    {  
        $pay_per_scan = $tech_pay[$key]['tot_pay']/$tech_scans[$key]['scans'];//calculate the payment per scan 
        $tech_per_scan[$key] = $pay_per_scan ; 
    }

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.