I have this array :
(
[id] => block_5df755210d30a
[name] => acf/floorplans
[data] => Array
(
[floorplans_0_valid_for_export] => 0
[floorplans_0_title] => title 1
[floorplans_0_house_area] => 40m²
[floorplans_0_bedrooms] => 1
[floorplans_1_valid_for_export] => 1
[floorplans_1_title] => title xx
[floorplans_1_house_area] => 90m²
[floorplans_1_bedrooms] => 2
[floorplans_2_valid_for_export] => 1
[floorplans_2_title] => title 2
[floorplans_2_house_area] => 50m²
[floorplans_2_bedrooms] => 1
[floorplans] => 3
)
)
As we can see in the data, we have fields (floorplans_X_valid_for_export
).
What I want to do is to get the data only when this field equal to 1
.
So from the given example, I want to keep only these fields:
[floorplans_1_valid_for_export] => 1
[floorplans_1_title] => title xx
[floorplans_1_house_area] => 90m²
[floorplans_1_bedrooms] => 2
[floorplans_2_valid_for_export] => 1
[floorplans_2_title] => title 2
[floorplans_2_house_area] => 50m²
[floorplans_2_bedrooms] => 1
My Answer:
> 1,
> [name] = "John",
> [age] = 25,
> [city] = "New York",
> [gender] = "male"
> )
I want to loop through this array and retain only the elements that relate to the key "city" with a value of "New York". Here's how you can achieve this in PHP:
php
$array = [
'id' => 1,
'name' => 'John',
'age' => 25,
'city' => 'New York',
'gender' => 'male'
];
$newArray = [];
foreach ($array as $key => $value) {
if ($key === 'city' && $value === 'New York') {
$newArray[$key] = $value;
}
}
print_r($newArray);
This code will output:
Array
(
[city] => New York
)
This way, you retain only the element with the key "city" and the value "New York" in a new array.
Rate this post
3 of 5 based on 2506 votesComments