英文:
Unable to convert indexed array to associative array in php
问题
The array $digit
can be transformed into the desired form as shown below:
'numbers' =>
array (
0 => 1,
1 => 2,
2 => 3,
),
To achieve this, you can use the following code:
$newDigitsArray = [];
foreach ($digit['numbers'] as $value) {
$newDigitsArray['numbers'][] = (int)$value;
}
\Log::info($newDigitsArray);
This code will convert the values in $digit['numbers']
from strings to integers and store them in the $newDigitsArray
in the desired format.
英文:
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?
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);
答案1
得分: 0
你可以使用内置的PHP方法 explode
来轻松实现这个功能:
$digits = ['numbers' => '1,2,3'];
$digits['numbers'] = explode(',', $digits['numbers']);
$digits
这是您提供的代码的翻译部分。
英文:
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",
],
]
>
答案2
得分: 0
你可以使用explode()函数来实现这个功能,
$digits = ['numbers' => '1,2,3'];
$digits['numbers'] = explode(',', $digits['numbers']);
print_r($digits);
输出:
'numbers' =>
array (
0 => 1,
1 => 2,
2 => 3,
),
英文:
Here you can use explode() to make this work,
$digits = ['numbers' => '1,2,3'];
$digits['numbers'] = explode(',', $digits['numbers']);
print_r($digits);
Output :
'numbers' =>
array (
0 => 1,
1 => 2,
2 => 3,
),
答案3
得分: -1
请尝试这段代码:
$digit = array();
$digit['numbers'] = array(1,2,3,4,5,6);
foreach($digit['numbers'] as $k => $v){
$num[] = $v;
}
$neo_digit['numbers'] = $num;
echo '<pre>'.print_r($neo_digit, true).'</pre>';
这是您提供的代码的中文翻译部分。
英文:
Try this code:
$digit = array();
$digit['numbers'] = array(1,2,3,4,5,6);
foreach($digit['numbers'] as $k => $v){
$num[] = $v;
}
$neo_digit['numbers'] = $num;
echo '<pre>'.print_r($neo_digit, true).'</pre>';
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论