php - 从php中的数组中获取值的索引

标签 php arrays foreach

我有下面的 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] => 
)

我必须从这个数组中获取元素 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

帮我解决这个问题?我的数组格式有问题吗?

最佳答案

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/

相关文章:

Java - 从 File[] 数组中删除一些文件

.net - 在 foreach 循环声明中使用 LINQ

php - mysql_num_rows() php - 它有效率吗?

c++ - 如何创建指向数组类成员的指针?

php - 我如何在 php 中写新行\r\n?

javascript - 如何从对象数组中的对象数组中搜索值?

javascript - 键值对未设置(如果未定义),但有默认值

php - foreach 循环未显示所需结果

JavaScript:解码 PHP json_encode 响应

php - 这是什么 : wp_nav_menu( array( 'theme_location' => 'primary' ) );