tags:

views:

255

answers:

2

I have a forcycle that contains a condition (and an incremental value i):

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

Thank you very much

A: 

You can write it somewhat more concise using the ?: operator:

$fieldname = ($condition? "value" : "string"); 
$arr[$i][$fieldname] = $node->nodeValue ;
xtofl
+1  A: 

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;
}
Petrunov
Almost there, with your code I get an array lke this:Array ( [0] => Array ( [value] => abc ) [1] => Array ( [string] => 0,999 ) [2] => Array ( [value] => meh ) [3] => Array ( [string] => 1,009 ))while i need to have a value and a string for each array's index:Array ( [0] => Array ( [value] => abc ) [0] => Array ( [string] => 0,999 ) [1] => Array ( [value] => meh ) [1] => Array ( [string] => 1,009 ))
0plus1
Actually adding:$result[$i][$type] = $node->nodeValue;Got me everything working as expected.Thank you
0plus1
I believe you need to do it like that: foreach( $nodes as $id => $node ) and then $result[$id][$type] = $node->nodeValue; I am sorry for missing that in the answer - haven't tested it :p
Petrunov
Tell me, what's the difference with my answer? Apart from verbosity?
xtofl
seems it's more appealing :p
Petrunov
OK. I can bear subjective :)
xtofl