[英]PHP: Better way to replace string value in array with an array?
I'm new to PHP so I'm not sure how to optimize this code. 我是PHP新手,所以不确定如何优化此代码。
I execute a Python script from PHP and the $output
variable returned is an array of arrays. 我从PHP执行Python脚本,返回的$output
变量是一个数组数组。
exec (" /Users/$USER/anaconda/bin/python /Applications/MAMP/cgi-bin/Evaluation1.py",$output)
Each array within the $output
array contains one string value separated by commas. $output
数组中的每个数组都包含一个字符串值,以逗号分隔。 So $output
is Array ( [0] => 1, 好, 0 [1] => 2, 妈妈, 3), etc. 因此$output
是Array([0] => 1,好,0 [1] => 2,2,妈妈,3),依此类推。
In each array within the $output
array, I use explode on the string value to create an array, and add it to my new $output
array called $output2
在$output
数组中的每个数组中,我对字符串值使用explode创建一个数组,并将其添加到名为$output2
新$output
数组中
$output2 = array();
foreach($output as $value){
$myArray = explode(',', $value);
$output2[] = $myArray;
}
Is there a way to just replace/overwrite the string value in the arrays within $output
with the new array, instead of adding each item to a new $output2
array? 有没有一种方法可以用新数组替换/覆盖$output
数组中的字符串值,而不是将每个项目添加到新的$output2
数组中?
You could use array_walk to do the loop over output. 您可以使用array_walk遍历输出。 You pass in a callback function that is called for each value by reference so any changes to the passed in value stick to the array. 您传入一个通过引用为每个值调用的回调函数,因此对传入值的任何更改都将保留在数组中。
Test data: 测试数据:
$output = array(
'1,A,2',
'2,B,3',
'3,C,4'
);
PHP >= 5.3.0 PHP> = 5.3.0
array_walk($output, function(&$val){ $val = explode(',', $val); } );
Older PHP 较旧的PHP
function mySplit(&$val){
$val = explode(',', $val);
}
array_walk($output, 'mySplit');
Both output: 两种输出:
Array
(
[0] => Array
(
[0] => 1
[1] => A
[2] => 2
)
[1] => Array
(
[0] => 2
[1] => B
[2] => 3
)
[2] => Array
(
[0] => 3
[1] => C
[2] => 4
)
)
Some great answers already. 已经有一些很好的答案。 Just adding this for completeness. 只是添加此内容是为了完整性。
$ar = array(
"1,2,3",
"4,5,6"
);
foreach($ar as $k => $v) {
$ar[$k] = explode(',', $v);
}
Wold be interesting to see aa performance difference of the different methods although i doubt it would be much. 看到不同方法的性能差异会很有趣,尽管我对此怀疑会很大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.