How Can I Select Data by Name From Array in PHP? - php

I have an array like this:
Array(
[0]=>Array([uploaderName]=>x[uploadedImageName]=>k6gIjfO[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[1]=>Array([uploaderName]=>x[uploadedImageName]=>byUTyJo[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[2]=>Array([uploaderName]=>x[uploadedImageName]=>oSVEnNk[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[3]=>Array([uploaderName]=>x[uploadedImageName]=>Dj7GRYS[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[4]=>Array([uploaderName]=>x[uploadedImageName]=>upsb8IC[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[5]=>Array([uploaderName]=>x[uploadedImageName]=>YoEEzGi[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[6]=>Array([uploaderName]=>x[uploadedImageName]=>st3dLNs[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[7]=>Array([uploaderName]=>x[uploadedImageName]=>LBNpiIG[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[8]=>Array([uploaderName]=>x[uploadedImageName]=>mFYDmBG[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[9]=>Array([uploaderName]=>x[uploadedImageName]=>z03kSx1[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
)
I want to get any image's data from this array.
Example: When user shows uploadedImageName == jCPjeWv, I wan't to get who is it's uploader.

Simple, just use foreach
$arr = array(/* content here */);
foreach($arr as $value){
if($value['uploadedImageName'] == 'jCPjeWv'){
echo $value['uploaderName'];
break;
}
}

Just for fun, here's another way:
echo array_column($array, 'uploaderName', 'uploadedImageName')['jCPjeWv'];
Get an array of uploaderName with the index set to uploadedImageName
Access the index using the uploadedImageName 'jCPjeWv'
Obviously to do it multiple times you would want to actually create a new array:
$images = array_column($array, 'uploaderName', 'uploadedImageName');
echo $images['jCPjeWv'];
If you want to access the other values as well, then use null instead of uploaderName:
$images = array_column($array, null, 'uploadedImageName');
echo $images['jCPjeWv']['uploaderName'];
echo $images['jCPjeWv']['uploaderIp'];
NOTE: These ways only work if the uploadedImageName is unique.

A foreach is possible, but I think it's important to learn the array functions as well so I'm just going to put this example here.
$uploadedImageName = 'jCPjeWv';
$filtered = array_filter($array, function($value) use ($uploadedImageName) {
return ($value['uploadedImageName'] == $uploadedImageName);
});
This will return a $filtered with the other arrays removed since their $value['uploadedImageName'] will not equal $uploadedImageName.
For more info check out the http://php.net/manual/en/function.array-filter.php manual.

Related

Is this the best way to convert between two different types of array?

I need to convert array like this
array(
0=>array("key"=>"key1", "val"=>"val1"),
1=>array("key"=>"key2", "val"=>"val2"),
2=>array("key"=>"key3", "val"=>"val3"),
)
To array like this
array(
"key1"=>"val1",
"key2"=>"val2",
"key3"=>"val3",
)
I do like below:
foreach($oldArray as $element){
$newArray[$element["key"]] = $element["val"];
}
Is this the best way to convert these arrays? (Especially if the array is huge.)
The least memory consuming way would be to use generators. Something like this should work, but I haven't tested it.
function flatten(array $inArray) {
foreach($inArray as $subArray) {
yield $subArray['key'] => $subArray['val'];
}
}
$newArray = iterator_to_array(flatten($oldArray));
Note: You need PHP 5.5+ for this.
Yes, the best way is using a foreach, even if your array is huge, that's not take many time.
Is your code working now? Else I can help you.
You can tell php to use foreach on their own like below.
$array = array(
0=>array("key"=>"key1", "val"=>"val1"),
1=>array("key"=>"key2", "val"=>"val2"),
2=>array("key"=>"key3", "val"=>"val3"),
);
$result = array();
array_walk($array, function($value) use (&$result) {
$result[$value['key']] = $value['val'];
});
echo '<pre>';
print_r($result);
echo '</pre>';

how to get the index of an array using the value in php

<?php
$interests[50] = array('fav_beverages' => "beer");
?>
now i need the index (i.e. 50 or whatever the index may be) from the value beer.
I tried array_search(), array_flip(), in_array(), extract(), list() to get the answer.
please do let me know if I have missed out any tricks for the above functions or any other function I`ve not listed. Answers will be greatly appreciated.
thanks for the replies. But for my disappointment it is still not working. btw I have a large pool of data like "beer");
$interests[50] = array('fav_cuisine' => "arabic");
$interests[50] = array('fav_food' => "hummus"); ?> . my approach was to get the other data like "arablic" and "hummus" from the user input "beer". So my only connection is via the index[50].Do let me know if my approach is wrong and I can access the data through other means.My senior just informed me that I`m not supposed to use loop.
This should work in your case.
$interests[50] = array('fav_beverages' => "beer");
function multi_array_search($needle, $interests){
foreach($interests as $interest){
if (array_search($needle, $interest)){
return array_search($interest, $interests);
break;
}
}
}
echo multi_array_search("beer", $interests);
If your array contains multiple sub-arrays and you don't know which one contains the value beer, then you can simply loop through the arrays, and then through the sub-arrays, to search for the value, and then return the index if it is found:
$needle = 'beer';
foreach ($interests as $index => $arr) {
foreach ($arr as $value) {
if ($value == $needle) {
echo $index;
break;
}
}
}
Demo

php arrays: search for matching values in a table and replace with array keys

Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray structure like #genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}

AND in a PHP foreach loop?

Is it possible to have an AND in a foreach loop?
For Example,
foreach ($bookmarks_latest as $bookmark AND $tags_latest as $tags)
You can always use a loop counter to access the same index in the second array as you are accessing in the foreach loop (i hope that makes sense).
For example:-
$i = 0;
foreach($bookmarks_latest as $bookmark){
$result['bookmark'] = $bookmark;
$result['tag'] = $tags_latest[$i];
$i++;
}
That should achieve what you are trying to do, otherwise use the approach sugested by dark_charlie.
In PHP 5 >= 5.3 you can use MultipleIterator.
Short answer: no. You can always put the bookmarks and tags into one array and iterate over it.
Or you could also do this:
reset($bookmarks_latest);
reset($tags_latest);
while ((list(, $bookmark) = each($bookmarks_latest)) && (list(,$tag) = each($tags_latest)) {
// Your code here that uses $bookmark and $tag
}
EDIT:
The requested example for the one-array solution:
class BookmarkWithTag {
public var $bookmark;
public var $tag;
}
// Use the class, fill instances to the array $tagsAndBookmarks
foreach ($tagsAndBookmarks as $bookmarkWithTag) {
$tag = $bookmarkWithTag->tag;
$bookmark = $bookmarkWithTag->bookmark;
}
you can't do that.
but you can
<?php
foreach($keyval as $key => $val) {
// something with $key and $val
}
the above example works really well if you have a hash type array but if you have nested values in the array I recommend you:
or option 2
<?php
foreach ($keyval as $kv) {
list($val1, $val2, $valn) = $kv;
}
No, but there are many ways to do this, e.g:
reset($tags_latest);
foreach ($bookmarks_latest as $bookmark){
$tags = current($tags_latest); next($tags_latest);
// here you can use $bookmark and $tags
}
No. No, it is not.
You'll have to manually write out a loop that uses indexes or internal pointers to traverse both arrays at the same time.
Yes, for completeness:
foreach (array_combine($bookmarks_latest, $tags_latest) as $bookm=>$tag)
That would be the native way to get what you want. But it only works if both input arrays have the exact same length, obviously.
(Using a separate iteration key is the more common approach however.)

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories