Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to convert indexed array to associative array in php

The array $digit now has data in this form :

'numbers' => 
  array (
    0 => '1,2,3',
  )

But I need that array in the below shown form:

'numbers' => 
  array (
    0 => 1,
    1 => 2,
    2 => 3,
  ),

How to achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried the below things. But all those are returning data in same form as I currently have .Any help is appreciated.

Method 1:

$newDigitsArray=[];
$i=0;
foreach( $digit[$i] as $key =>$value) { 
    $newDigitsArray['numbers']= [$i => $value];
    $i++;
}
\Log::info($newDigitsArray);

Method 2:

$newDigitsArray=[];
for($i=0;$i<count($digit);){
    $newDigitsArray[$i]=$digit[$i];
    $i++;
}
 \Log::info($newDigitsArray);

>Solution :

You can use the built-in php method explode to achieve this easily:

> $digits = ['numbers' => '1,2,3']
= [
    "numbers" => "1,2,3",
  ]

> $digits['numbers'] = explode(',', $digits['numbers'])
= [
    "1",
    "2",
    "3",
  ]

> $digits
= [
    "numbers" => [
      "1",
      "2",
      "3",
    ],
  ]

>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading