我有下面的 php 数组 $tempStyleArray
,它是通过吐出一个字符串创建的。
$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] =>
)
我必须从这个数组中获取元素 height
的 index/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
帮我解决这个问题?我的数组格式有问题吗?
最佳答案
foreach($tempStyleArray as $value)
{
if($value == "height") // not satisfying this condition
{
echo $value;
echo '</br>';
$key = $i;
}
}
$i 是什么?最好使用 key=>value for。
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"];
这样会更快,而且您不必再进行搜索。
更新:
for( $i == 1; $i < count($tempStyleArray); $i = $i+2)
{
$newArray[ $tempStyleArray[$i-1] ] = $tempStyleArray[$i]
}
你可以得到一个基于散列的数组。
关于php - 从php中的数组中获取值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29788644/