Find value in multidimensional array by another key and value - php

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;
}
}

$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];

foreach($zdjecia as $zdjecie) {
foreach($zdjecie as $key=>$value) {
if($key == "image-type" && $value == "2") {
$zdjecie_aukcji = $zdjecie['image-url'];
}
}
}

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/...
Working example

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
}
Working Demo

Add break; right after
$zdjecie_aukcji = $key['image-url'];

modify to:
$zdjecia = $array['item-img-list'];
foreach($zdjecia as $zdjecie) {
if($zdjecie['image-type'] == '2') {
$zdjecie_aukcji = $zdjecie['image-url'];
}
}

Related

PHP Using an If-else inside multidimensional associative array

My multidimensional associative array :
$search_cookies = array(
"type_catalog" => $type_array,
"size_catalog" => $size_array,
"color_catalog" => $color_array,
);
I need to do that :
$search_cookies = array(
if(isset($type_array){
"type_catalog" => $type_array,
}
elseif(isset($size_array)){
"size_catalog" => $size_array,
}
elseif(isset($color_array)){
"color_catalog" => $color_array,
}
);
Here is the entire code if you think it must be some other way :
$first_array = array('t-1', 's-32', 't-2', 's-36');
function removeLetters($row){
return preg_replace("/[^0-9,.]/", "", $row);
}
foreach($first_array as $row){
$exp_key = explode('-', $row);
if($exp_key[0] == 't'){
$type_array[] = removeLetters($row);
}
if($exp_key[0] == 's'){
$size_array[] = removeLetters($row);
}
if($exp_key[0] == 'c'){
$color_array[] = removeLetters($row);
}
}
$search_cookies = array(
"type_catalog" => $type_array,
"size_catalog" => $size_array,
"color_catalog" => $color_array,
);
you can try this:
$search_cookies = array();
if(isset($type_array)){
$search_cookies["type_catalog"] = $type_array;
}
if(isset($size_array)){
$search_cookies["size_catalog"] = $size_array;
}
if(isset($color_array)){
$search_cookies["color_catalog"] = $color_array;
}

PHP - Arrays and Foreach

I searched in Google and consulted the PHP documentation, but couldn't figure out how the following code works:
$some='name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
return $addons;
}
echo (count( getActiveAddons( $some ) ) ? implode( '<br />', getActiveAddons( $some ) ) : 'None');
The code always echo's None.
Please help me in this.
I don't know where you got this code from but you've initialized $some the wrong way. It is expected as an array like this:
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon'
'nextduedate' => '2013-04-11',
'status' => 'Active'
)
);
I guess the article you've read is expecting you to parse the original string into this format.
You can achieve this like this:
$string = 'name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
$result = array();
foreach(explode('|', $string) as $record) {
$item = array();
foreach(explode(';', $record) as $column) {
$keyval = explode('=', $column);
$item[$keyval[0]] = $keyval[1];
}
$result[]= $item;
}
// now call your function
getActiveAddons($result);
$some is not an array so foreach will not operate on it. You need to do something like
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon',
'nextduedate' => '2013-04-11',
'status'=> 'Active'
)
);
This will create a multidimensional array that you can loop through.
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
foreach($addon as $key => $value) {
if ($key == 'status' && $value == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
}
return $addons;
}
First, your $some variable is just a string. You could parse the string into an array using explode(), but it's easier to just start as an array:
$some = array(
array(
"name" => "Licensing Module",
"nextduedate" => "2013-04-10",
"status" => "Active",
),
array(
"name" => "Test Addon",
"nextduedate" => "2013-04-11",
"status" => "Active",
)
);
Now, for your function, you are on the right track, but I'll just clean it up:
function getActiveAddons($somet) {
if (!is_array($somet)) {
return false;
}
$addons = array();
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
}
}
if (count($addons) > 0) {
return $addons;
}
return false;
}
And finally your output (you were calling the function twice):
$result = getActiveAddons($some);
if ($result === false) {
echo "No active addons!";
}
else {
echo implode("<br />", $result);
}

PHP multiple arrays to one associative array

How can I merge this three arrays
$name ={"Tom", "John", "David"};
$v1 = {"Tom":100, "David":200};
$v2 = {"John":500, "Tom":400};
into one multidimensional associative array in two different ways?
One way is the key order should be same as that of array "name".
$name_merged_original_order = array (
"Tom" => Array(
"v1" => 100,
"v2" => 400
),
"John" => Array(
"v1" => "N/A",
"v2" => 500
),
"David" => Array(
"v1" => 100,
"v2" => "N/A"
)
)
Another ways is the alphabetical of array "name":
$name_merged_asc = array (
"David" => Array(
"v1" => 100,
"v2" => "N/A"
),
"John" => Array(
"v1" => "N/A",
"v2" => 200
),
"Tom" => Array(
"v1" => 100,
"v2" => 400
),
)
The tricky part is that array "v1" and "v2" is not ordered as the key of "name." They also don't have all keys as in "name." Thanks!
It's not tested and the easiest solution:
$name_merged_original_order = array();
foreach($name as $key){
$name_merged_original_order[$key] = array();
if(array_key_exists($key, $v1)){
$name_merged_original_order[$key]['v1'] = $v1[$key];
}
else{
$name_merged_original_order[$key]['v1'] = 'N/A';
}
if(array_key_exists($key, $v2)){
$name_merged_original_order[$key]['v2'] = $v2[$key];
}
else{
$name_merged_original_order[$key]['v2'] = 'N/A';
}
}
sort($name);
$name_merged_asc = array();
foreach($name as $key){
$name_merged_asc[$key] = array();
if(array_key_exists($key, $v1)){
$name_merged_asc[$key]['v1'] = $v1[$key];
}
else{
$name_merged_asc[$key]['v1'] = 'N/A';
}
if(array_key_exists($key, $v2)){
$name_merged_asc[$key]['v2'] = $v2[$key];
}
else{
$name_merged_asc[$key]['v2'] = 'N/A';
}
}
As I understand you would like something like that:
$name = array("Tom", "John", "David");
$result = array();
$v1 = array("Tom" => "200", "John" => "100", "David" => "10");
$v2 = array("Tom" => "254", "David" => "156");
$vars = array("v1", "v2");
foreach($name as $n)
{
$result[$n] = array();
foreach($vars as $v)
{
if(array_key_exists($n, ${$v}))
$result[$n][$v] = ${$v}[$n];
}
}
I hope $result is what you need.
For Example, you have these arrays:
<?php
$FirstArrays = array('a', 'b', 'c', 'd');
$SecArrays = array('1', '2', '3', '4');
1)
foreach($FirstArrays as $index => $value) {
echo $FirstArrays[$index].$SecArrays[$index];
echo "<br/>";
}
or 2)
for ($index = 0 ; $index < count($FirstArrays); $index ++) {
echo $FirstArrays[$index] . $SecArrays[$index];
echo "<br/>";
}
Assume from your comments you only want items that match in all 3 arrays:
for( $i=0; $i< count($name) ; $i++){
if( !empty( $v1[ $name[$i]]) && !empty( $v2[ $name[$i]]) ){
$newArray[$name[$i]]= array( 'v1'=> $v1[ $name[$i]], 'v2'=> $v2[ $name[$i]]):
}
}
To sort:
asort($newArray);

php, long and deep matrix

I have a deep and long array (matrix). I only know the product ID.
How found way to product?
Sample an array of (but as I said, it can be very long and deep):
Array(
[apple] => Array(
[new] => Array(
[0] => Array([id] => 1)
[1] => Array([id] => 2))
[old] => Array(
[0] => Array([id] => 3)
[1] => Array([id] => 4))
)
)
I have id: 3, and i wish get this:
apple, old, 0
Thanks
You can use this baby:
function getById($id,$array,&$keys){
foreach($array as $key => $value){
if(is_array( $value )){
$result = getById($id,$value,$keys);
if($result == true){
$keys[] = $key;
return true;
}
}
else if($key == 'id' && $value == $id){
$keys[] = $key; // Optional, adds id to the result array
return true;
}
}
return false;
}
// USAGE:
$result_array = array();
getById( 3, $products, $result_array);
// RESULT (= $result_array)
Array
(
[0] => id
[1] => 0
[2] => old
[3] => apple
)
The function itself will return true on success and false on error, the data you want to have will be stored in the 3rd parameter.
You can use array_reverse(), link, to reverse the order and array_pop(), link, to remove the last item ('id')
Recursion is the answer for this type of problem. Though, if we can make certain assumptions about the structure of the array (i.e., 'id' always be a leaf node with no children) there's further optimizations possible:
<?php
$a = array(
'apple'=> array(
'new'=> array(array('id' => 1), array('id' => 2), array('id' => 5)),
'old'=> array(array('id' => 3), array('id' => 4, 'keyname' => 'keyvalue'))
),
);
// When true the complete path has been found.
$complete = false;
function get_path($a, $key, $value, &$path = null) {
global $complete;
// Initialize path array for first call
if (is_null($path)) $path = array();
foreach ($a as $k => $v) {
// Build current path being tested
array_push($path, $k);
// Check for key / value match
if ($k == $key && $v == $value) {
// Complete path found!
$complete= true;
// Remove last path
array_pop($path);
break;
} else if (is_array($v)) {
// **RECURSION** Step down into the next array
get_path($v, $key, $value, $path);
}
// When the complete path is found no need to continue loop iteration
if ($complete) break;
// Teardown current test path
array_pop($path);
}
return $path;
}
var_dump( get_path($a, 'id', 3) );
$complete = false;
var_dump( get_path($a, 'id', 2) );
$complete = false;
var_dump( get_path($a, 'id', 5) );
$complete = false;
var_dump( get_path($a, 'keyname', 'keyvalue') );
I tried this for my programming exercise.
<?php
$data = array(
'apple'=> array(
'new'=> array(array('id' => 1), array('id' => 2), array('id' => 5)),
'old'=> array(array('id' => 3), array('id' => 4))
),
);
####print_r($data);
function deepfind($data,$findfor,$depth = array() ){
foreach( $data as $key => $moredata ){
if( is_scalar($moredata) && $moredata == $findfor ){
return $depth;
} elseif( is_array($moredata) ){
$moredepth = $depth;
$moredepth[] = $key;
$isok = deepfind( $moredata, $findfor, $moredepth );
if( $isok !== false ){
return $isok;
}
}
}
return false;
}
$aaa = deepfind($data,3);
print_r($aaa);
If you create the array once and use it multiple times i would do it another way...
When building the initial array create another one
$id_to_info=array();
$id_to_info[1]=&array['apple']['new'][0];
$id_to_info[2]=&array['apple']['new'][2];

Get array's key recursively and create underscore separated string

Right now i got an array which has some sort of information and i need to create a table from it. e.g.
Student{
[Address]{
[StreetAddress] =>"Some Street"
[StreetName] => "Some Name"
}
[Marks1] => 100
[Marks2] => 50
}
Now I want to create database table like which contain the fields name as :
Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2
It should be recursive so from any depth of array it can create the string in my format.
You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$key = $iterator->getSubIterator($i)->key() . '_' . $key;
}
$keys[] = $key;
}
var_export($keys);
The above example outputs something like:
array (
0 => 'Student_Address_StreetAddress',
1 => 'Student_Address_StreetName',
2 => 'Student_Marks1',
3 => 'Student_Marks2',
)
(Working on it, here is the array to save the trouble):
$arr = array
(
'Student' => array
(
'Address' => array
(
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => '100',
'Marks2' => '50',
),
);
Here it is, using a modified version of #polygenelubricants code:
function dfs($array, $parent = null)
{
static $result = array();
if (is_array($array) * count($array) > 0)
{
foreach ($array as $key => $value)
{
dfs($value, $parent . '_' . $key);
}
}
else
{
$result[] = ltrim($parent, '_');
}
return $result;
}
echo '<pre>';
print_r(dfs($arr));
echo '</pre>';
Outputs:
Array
(
[0] => Student_Address_StreetAddress
[1] => Student_Address_StreetName
[2] => Student_Marks1
[3] => Student_Marks2
)
Something like this maybe?
$schema = array(
'Student' => array(
'Address' => array(
'StreetAddresss' => "Some Street",
'StreetName' => "Some Name",
),
'Marks1' => 100,
'Marks2' => 50,
),
);
$result = array();
function walk($value, $key, $memo = "") {
global $result;
if(is_array($value)) {
$memo .= $key . '_';
array_walk($value, 'walk', $memo);
} else {
$result[] = $memo . $key;
}
}
array_walk($schema, 'walk');
var_dump($result);
I know globals are bad, but can't think of anything better now.
Something like this works:
<?php
$arr = array (
'Student' => array (
'Address' => array (
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => array(),
'Marks2' => '50',
),
);
$result = array();
function dfs($data, $prefix = "") {
global $result;
if (is_array($data) && !empty($data)) {
foreach ($data as $key => $value) {
dfs($value, "{$prefix}_{$key}");
}
} else {
$result[substr($prefix, 1)] = $data;
}
}
dfs($arr);
var_dump($result);
?>
This prints:
array(4) {
["Student_Address_StreetAddress"] => string(11) "Some Street"
["Student_Address_StreetName"] => string(9) "Some Name"
["Student_Marks1"] => array(0) {}
["Student_Marks2"] => string(2) "50"
}
function getValues($dataArray,$strKey="")
{
global $arrFinalValues;
if(is_array($dataArray))
{
$currentKey = $strKey;
foreach($dataArray as $key => $val)
{
if(is_array($val) && !empty($val))
{
getValues($val,$currentKey.$key."_");
}
else if(!empty($val))
{
if(!empty($strKey))
$strTmpKey = $strKey.$key;
else
$strTmpKey = $key;
$arrFinalValues[$strTmpKey]=$val;
}
}
}
}

Categories