2015-04-22 112 views
4

我有下面的php数组$tempStyleArray,它是通过spiting一个字符串创建的。从php中的数组获取值的索引

$tempStyleArray = preg_split("/[:;]+/", "width: 569px; height: 26.456692913px; margin: 0px; border: 2px solid black;"); 


Array 
(
    [0] => width 
    [1] => 569px 
    [2] => height 
    [3] => 26.456692913px 
    [4] => margin 
    [5] => 0px 
    [6] => border 
    [7] => 2px solid black 
    [8] => 
) 

我得从这个数组元素heightindex/key。我尝试了下面的代码,但似乎没有为我工作。

foreach($tempStyleArray as $value) 
{ 
    if($value == "height") // not satisfying this condition 
    { 
    echo $value; 
    echo '</br>'; 
    $key = $i; 
    } 
} 
在上述方案

它不会永远满足条件:(

$key = array_search('height', $tempStyleArray); // this one not returning anything 

帮我解决这个问题?有没有我的阵列格式的任何问题?

回答

2

试试这个 -

$tempStyleArray = array_map('trim', preg_split("/[:;]+/", "width: 569px; height: 26.456692913px; margin: 0px; border: 2px solid black;")); 
var_dump($tempStyleArray); 
$key = array_search('height', $tempStyleArray); 
echo $key; 

它发生,因为有spacearray值。所以需要成为trimmed。分割字符串后,每个值都将通过trim(),以便white spaces被删除。如下

+0

那么如何将我的数组转换为这种格式? – chriz

+0

你是如何得到这个数组的? –

1

在你的代码有错误请尝试:

foreach($tempStyleArray as $key => $value) 
{ 
    if($value == "height") 
    { 
    echo $key; 
    } 
} 
4
foreach($tempStyleArray as $value) 
{ 
    if($value == "height") // not satisfying this condition 
    { 
    echo $value; 
    echo '</br>'; 
    $key = $i; 
    } 
} 

和$ i是什么,最好使用key => value。在你的阵列

foreach($tempStyleArray as $key => $value) 
{ 
    if($value == "height") // not satisfying this condition 
    { 
    echo $value; 
    echo '</br>'; 
    echo $key; 
    } 
} 

来看,似乎想要说“宽度”将是569px,那么也许是更好地做到这一点:

$tempStyleArray = array(
    "width" => "569px", 
    "height" => "26.456692913px", 
    "margin" => "0px", 
    "border" => "2px solid black" 
); 

这样,你可以只说

echo $tempStyleArray["width"]; 

这会更快,你不必因为搜索而应付。

UPDATE:

for($i == 1; $i < count($tempStyleArray); $i = $i+2) 
{ 
    $newArray[ $tempStyleArray[$i-1] ] = $tempStyleArray[$i] 
} 

用,你可以得到一个基于散列的数组。

+0

我不好,这个解决方案没有工作..但你的建议是巨大的。检查我编辑的问题..我通过分割一个字符串生成这个数组,我怎么可以让我的数组像我建议? – chriz

+1

更新,如果你的“数组”会很大,你需要查询很多,这会比使用array_search更好。 – lcjury

2

您从阵列

采取错误的价值观应该是

foreach($tempStyleArray as $temp => $value) { 
    if($value == "height") // will satisfy this condition 
    { 
     echo $value; 
     echo '</br>'; 
     $key = $i; 
    } 
} 
2

使用(像对待一个associative阵列)

foreach($tempStyleArray as $key => $value){ 
    if($value == "height") // not satisfying this condition 
    { 
    echo $value; 
    echo '</br>'; 
    echo $key; 
    } 
}