我为此疯狂。 所以,让我说我得到了这个数组:
Array
(
[0] => Array
(
[variation_name] => variation_1
[license_type] => Array
(
[slug] => license_x
[price] => price_x
[dimensions] => dimensions_x
)
)
[1] => Array
(
[variation_name] => variation_2
[license_type] => Array
(
[slug] => license_y
[price] => price_y
[dimensions] => dimensions_y
)
)
[2] => Array
(
[variation_name] => variation_3
[license_type] => Array
(
[slug] => license_solid_z
[price] => price_z
[dimensions] => dimensions_z
)
)
)
我希望回显以“license_solid”开头的数组值以及包含它的数组的值。 要获得“license_solid”条目,我运行以下命令:
$attribute_pa_licenses = array_column($array, 'license_type');
$attribute_pa_license_slug = array_column($attribute_pa_licenses, 'slug');
foreach ($attribute_pa_license_slug as $value) {
if (0 === strpos($value, 'license_solid')) {
echo $value;
}
}
它可以工作,但我不知道如何回应数组“包含”$ value 在这个例子中,它应该给出variation_3
答案 0 :(得分:1)
重写你的foreach循环如下: -
foreach ($attribute_pa_license_slug as $value) {
if(!empty($value['license_type']['slug'])){
$slug = $value['license_type']['slug'];
if (strpos($slug, 'license_solid') !== false) {
echo $slug; // echo your matched value
$data[] = $value; // store your array in data array
}
}
}
print_r($data); // print arrays who has valid slug values
答案 1 :(得分:1)
传统的foreach
适用于已知结构的数组,但对于结构未知的大型数组array iterator来说是好的。
看看下面的两个方法
<?php
$array = Array
(
'0' => Array
(
'variation_name' => 'variation_1',
'license_type' => Array
(
'slug' => 'license_x',
'price' => 'price_x',
'dimensions' => 'dimensions_x'
)
),
'1' => Array
(
'variation_name' => 'variation_2',
'license_type' => Array
(
'slug' => 'license_y',
'price' => 'price_y',
'dimensions' => 'dimensions_y'
)
),
'2' => Array
(
'variation_name' => 'variation_3',
'license_type' => Array
(
'slug' => 'license_solid_z',
'price' => 'price_z',
'dimensions' => 'dimensions_z'
)
)
);
//METHOD 1 - For known structured array
foreach($array AS $key => $val) {
$slug = $val['license_type']['slug'];
if (strpos($slug, 'license_solid') !== false) {
$data[] = $array[$key];
}
}
print_r($data);
//METHOD 2 - For unknown structured array (use iterator for unknow and large structured)
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$data = array();
foreach ($it as $key => $val) {
$ar = $it->getSubIterator($it->getDepth() - 1);
if($key == 'slug' && strpos($val, 'license_solid') !== false){
$data[] = (array) $ar;
}
}
print_r($data);
输出:
Array
(
[0] => Array
(
[variation_name] => variation_3
[license_type] => Array
(
[slug] => license_solid_z
[price] => price_z
[dimensions] => dimensions_z
)
)
)
答案 2 :(得分:0)
使用带有$key
参数的整个数组使用foreach:
foreach ($array as $key => $value) {
$slugValue = $value['license_type']['slug'];
if (...) { echo $slugValue; }
// $key contains current array index (0..2 for array in example)
// $value contains array with variation_name, license_type
}