[英]I need to push into an array values based on a specific condition, what is the correct way to do this?
I have a forcycle that contains a condition (and an incremental value i): 我有一个包含条件(和增量值i)的forcycle:
if(condition)){$arr[$i] = array("value" => $node->nodeValue));}
else{$arr[$i] = array("string" => $node->nodeValue);}
In the end I need to have an array like this: 最后,我需要一个像这样的数组:
Array ( [1] => Array ( [string] => abc [value] => 0,999 )
[2] => Array ( [string] => meh [value] => 0,123 )
[x] => Array ( [string] => xxx [value] => xxx ) )
I understand that my code doesn't work, I think I should use array_push, but I was wondering is there are better way to achieve this 我知道我的代码行不通,我认为我应该使用array_push,但我想知道是否有更好的方法可以实现此目的
Thank you very much 非常感谢你
I'm sorry, the question is not very clear.. Is that what you are trying to do? 对不起,这个问题不是很清楚。那是您要做什么?
$result = array();
foreach( $nodes as $node )
{
$type = 'value';
if( is_string( $node->nodeValue ) )
{
$type = 'string';
}
$result[][$type] = $node->nodeValue;
}
You can write it somewhat more concise using the ?: operator: 您可以使用?:运算符将其编写得更加简洁:
$fieldname = ($condition? "value" : "string");
$arr[$i][$fieldname] = $node->nodeValue ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.