PHP多维数组处理-查找数组深度为2的值
我在访问数组中的数据时遇到了一些问题,如下所示:PHP多维数组处理-查找数组深度为2的值,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我在访问数组中的数据时遇到了一些问题,如下所示: array ( 0 => array ( 'value' => '46', 'label' => 'Brand A', ), 1 => array ( 'value' => '45', 'label' => 'Brand B', ), 2 => array ( 'value' => '570', 'label' => 'Brand C', ), ); 基本上,
array (
0 => array ( 'value' => '46', 'label' => 'Brand A', ),
1 => array ( 'value' => '45', 'label' => 'Brand B', ),
2 => array ( 'value' => '570', 'label' => 'Brand C', ),
);
基本上,我希望在给定值时能够返回标签的内容(例如,45返回品牌B),但不确定如何在这些级别内执行此操作
我是否需要通过某种循环将这个数组分解成更小的块来访问这些数据
感谢您在创建数组时需要将值用作键:
array(
'46' => 'Brand A',
'45' => 'Brand B',
);
或
等等
如果您不是创建数组的人,那么您可以foreach
循环遍历它,并将其重新加工成不同的结构。试试这个
<?php
$arr = array (
0 => array ( 'value' => '46', 'label' => 'Brand A', ),
1 => array ( 'value' => '45', 'label' => 'Brand B', ),
2 => array ( 'value' => '570', 'label' => 'Brand C', ),
);
foreach($arr as $ele){
echo "value=".$ele['value']." and label=".$ele['label'];
}
?>
Whathaveyoutried.com?我给你一个提示。Foreach循环、google多维数组搜索、in_数组、array_搜索等。你真正的问题是你没有使用这些标签作为键。我会选择使用标签作为键而不是值,但重点是-原始数组不需要是多维的。我同意,但是,它是通过API调用以这种方式输出的。我可能应该问一下,如何最好地重新构造数组以删除不必要的维度,不过还是要谢谢你。
<?php
$arr = array (
0 => array ( 'value' => '46', 'label' => 'Brand A', ),
1 => array ( 'value' => '45', 'label' => 'Brand B', ),
2 => array ( 'value' => '570', 'label' => 'Brand C', ),
);
foreach($arr as $ele){
echo "value=".$ele['value']." and label=".$ele['label'];
}
?>
<?php
$arr = array (
0 => array ( 'value' => '46', 'label' => 'Brand A', ),
1 => array ( 'value' => '45', 'label' => 'Brand B', ),
2 => array ( 'value' => '570', 'label' => 'Brand C', ),
);
$val = 45; // search for 45
foreach($arr as $vals){
if($vals['value'] == $val){
echo "value=".$vals['value'];
echo "<br>";
echo "label=".$vals['label'];
}
}
?>