Reputation: 87
I have the following array:
$array = array(
'item-img-list' => array(
array(
'image-type' => 1,
'image-url' => 'http://img07.allegroimg.pl/...'
),
array(
'image-type' => 2,
'image-url' => 'http://img07.allegroimg.pl/...'
),
array(
'image-type' => 3,
'image-url' => 'http://img07.allegroimg.pl/...'
)
)
)
How to get first 'image-url' value where 'image-type' = '2'? I'm trying do that by this code but nothing:
$zdjecia = $item['item-img-list'];
foreach($zdjecia as $zdjecie) {
foreach($zdjecie as $key=>$value) {
if($key == "image-type" && $value == "2") {
$zdjecie_aukcji = $key['image-url'];
}
}
}
Thank you for any kind of help!
Works!
$searchKey = 2;
foreach($zdjecia as $zdjecie) {
if (**$zdjecie->{'image-type'}** == $searchKey){
$zdjecie_aukcji = **$zdjecie->{'image-url'}**;
break;
}
}
Upvotes: 3
Views: 170
Reputation: 350
modify to:
$zdjecia = $array['item-img-list'];
foreach($zdjecia as $zdjecie) {
if($zdjecie['image-type'] == '2') {
$zdjecie_aukcji = $zdjecie['image-url'];
}
}
Upvotes: 2
Reputation: 7762
why not simply this:-
$array = array(
'item-img-list' => array(
array(
'image-type' => 1,
'image-url' => 'http://img07.allegroimg.pl/...'
),
array(
'image-type' => 2,
'image-url' => 'http://img07.allegroimg.pl/...'
),
array(
'image-type' => 3,
'image-url' => 'http://img07.allegroimg.pl/...'
)
)
);
$newArray = array();
foreach($array['item-img-list'] as $k=>$v){
$newArray[$v['image-type']] = $v['image-url'];
}
Output :-
Array
(
[1] => http://img07.allegroimg.pl/...
[2] => http://img07.allegroimg.pl/...
[3] => http://img07.allegroimg.pl/...
)
or
echo $newArray[2];
you can also check key like this:
if (array_key_exists(2, $newArray)) {
// Do whatever you want
}
Upvotes: 2
Reputation: 13412
A suggestions with custom function that I use for my project to find a value by key in multidimensional array:
function array_search_multi($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, array_search_multi($subarray, $key, $value));
}
return $results;
}
Usage:
$results = array_search_multi($array, 'image-type', '2');
echo $results[0]['image-url'];
Output:
http://img07.allegroimg.pl/...
Upvotes: 2
Reputation: 212412
$zdjecia = $item['item-img-list'];
$searchKey = 2;
foreach($zdjecia as $zdjecie) {
if ($zdjecie['image-type'] == $searchKey)
$zdjecie_aukcji = $zdjecie['image-url'];
break;
}
}
or (PHP >=5.5)
$zdjecia = $item['item-img-list'];
$searchKey = 2;
$results = array_column(
$zdjecia,
'image-url',
'image-type'
);
$zdjecie_aukcji = $results[$searchKey];
Upvotes: 2
Reputation: 781
foreach($zdjecia as $zdjecie) {
foreach($zdjecie as $key=>$value) {
if($key == "image-type" && $value == "2") {
$zdjecie_aukcji = $zdjecie['image-url'];
}
}
}
Upvotes: 2