Skip to content
Advertisement

Function to return a associative array in php from another array

I am new in learning php and array . I have to create an associative array from another array . In addition The array must be returned in alphabetical order based upon the key names.

this is the input array

        $customerTransactions = [
        'bill=9898',
        'bob=772',
        'james=2672',
        'jim=9872',
        'luke=2665',
        'jim=10000'
    ];

The output array should be like

$outputarray = [
            'bill' => 9898,
            'bob' => 772,
            'james' => 2672,
            'jim' => 19872,
            'luke' => 2665
        ],

I am trying to create a function which will return the output array .

public function getCustomerBalances($customerTransactions)
{
      $max = sizeof($customerTransactions);     
      $str = implode(",", $customerTransactions);     

      $outputarray = print_r (explode("=",$str));

      return array($outputarray); 
}

But result of this array is this this

Array(
[0] => bill
[1] => 9898,bob
[2] => 772,james
[3] => 2672,jim
[4] => 9872,luke
[5] => 2665,jim
[6] => 10000)

What can I do to correct it

Advertisement

Answer

You want to use explode not implode.

Below I have looped through your array of strings and explode each of the values in the array by the equals operator to get a new array that holds both the customer name and the transaction ID.

I am then populating a new array called $data with the results from this explosion, the first element in the $result array is the customer name, and the second element is the transaction ID.


Once you’ve got the array outputing correctly, you mentioned you wanted to order them alphabetically, to do this you would use ksort().

This is simple enough, you’d just need to call this function on the output array like so:

ksort($data);


This should work for you:

public function getCustomerBalances($transactions) {

    $data = [];

    foreach($transactions as $v) {
        $result = explode('=', $v);
        $data[$result[0]] = $result[1];
    }

    ksort($data);

    return $data; 

}

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement