In my application I am using array_diff function as -
$aDeleteCountryCodes = array_diff($aCurrentCountryCodes, $aNewCountryCodes);
Now what happens is, the resultant array, $aDeleteCountryCodes, some times comes as
Array
(
[2] => 213
)
and some times
Array
(
[2] => 213
[3] => 355
)
which messes my for loop that I use to delete records from database. For loop is like this-
for ($i=0; $i <= count($aDeleteCountryCodes); $++)
{
// Delete record $aDeleteCountryCodes[$i]
}
what I want is the array to come as -
Array
(
[0] => 213
)
Array
(
[0] => 213
[1] => 355
)
so that the looping becomes easier. I hope I made it clear. How can I do this ?
Use array_values.
Use foreach instead of "manual for loops."
Rather than reset the keys, it's preferable to just iterate over the existing keys:
foreach ($aDeleteCountryCodes as $key => $value) {
// delete goes here.
}
Use array_values(array_diff($aCurrentCountryCodes, $aNewCountryCodes));
You can just get the values out into a new array:
$aDeleteCountryCodes = array_values($aDeleteCountryCodes) //Keys resetted.
Related
I have a multidimensional array like this:
Array (
[0] => Array
(
[time] => 1364685993
[memberid] => 131
)
[1] => Array
(
[time] => 1364685994
[memberid] => 133
)
[2] => Array
(
[time] => 1364685995
[memberid] => 141
)
)
and a single-dimensional array like this:
Array (
[0] => 131
[1] => 141
[2] => 191
[3] => 205
)
Now I want to remove all Sub-arrays from multidimensional arrays that DOES NOT contain the memberid value from normal array ?
In this case only Subaray[1] to be removed from multidimensional array as it's 'memberid' key value (133) doesn't show in normal array. Those arrays are actually pretty big, so I am not sure what would be fastest way to do it ?
$normalArray = array_flip($normalArray);
$multiDimArray = array_filter($multiDimArray, function ($elem) use ($normalArray) {
return isset($normalArray[$elem['memberid']]);
});
Requires exactly two iterations, one over each array. Key lookups using $normalArray[$elem['memberId']] are blazingly fast. May have some memory overhead due to the functional nature and copies of arrays, use a traditional loop and unset if that's an issue.
First, I would flip the $nomal array to get constant lookup time into the array, like this:
$normal = array_flip( $normal);
Then, you just have to filter the $multidimensional_array by the $normal array with a simple lookup:
$filtered = array_filter( $multidimensional_array, function( $el) use( $normal) {
return isset( $normal[ $el['member_id'] ]);
});
Don't have access to development resources at the moment to test but this should work.
foreach($members as $member => $property) {
if (!in_array($property['member_id'], $id_array)) {
unset($members[$member]);
}
}
$id_array is the 1-dimensional matrix (array) you've put in your question.
Instead of filtering the database results after the fact you may want to use the single-dimensional array in the database query itself.
We do not know what the query, you are using, looks like, but something along these lines would do it:
// The ids from the file
$use_ids = array(131, 141, 191, 205);
// Create a list for the IN clause
$ids = '(' . implode(',', $use_ids) . ')';
// Create the query
$query = <<< SQL
SELECT time, memberid
FROM some_table
WHERE ...
AND memberid IN {$ids}
ORDER BY time
SQL;
// Execute the query, etc.
It is always a good idea to let the SQL handle as much filtering of content as possible.
i have array like
Array
(
[1] => Array
(
[user_info] => Array
(
[id] => 1
[name] => Josh
[email] => u0001#josh.com
[watched_auctions] => 150022 150031
)
[auctions] => Array
(
[150022] => Array
(
[id] => 150022
[title] => Title of auction
[end_date] => 2013-08-28 17:50:00
[price] => 10
)
[150031] => Array
(
[id] => 150031
[title] => Title of auction №
[end_date] => 2013-08-28 16:08:03
[price] => 10
)
)
)
so i need put in <td> info from [auctions] => Array where is id,title,end_date but when i do like $Info['id'] going and put id from [user_info] when i try $Info[auctions]['id'] there is return null how to go and get [auctions] info ?
Try:
foreach( $info['auctions'] as $key=>$each ){
echo ( $each['id'] );
}
Or,
foreach( $info as $key=>$each ){
foreach( $each['auctions'] as $subKey=>$subEach ){
echo ( $subEach['id'] );
}
}
Given the data structure from your question, the correct way would be for example:
$Info[1]['auctions'][150031]['id']
$array =array();
foreach($mainArray as $innerArray){
$array[] = $innerArray['auctions'];
}
foreach($array as $key=>$val){
foreach($val as $k=>$dataVal){
# Here you will get Value of particular key
echo $dataVal[$k]['id'];
}
}
Try this code
Your question is a bit malformed. I don't know if this is due to a lacking understanding of the array structure or just that you had a hard time to explain. But basically an array in PHP never has two keys. I will try to shed some more light on the topic on a basic level and hope it helps you.
Anyway, what you have is an array of arrays. And there is no difference in how you access the contents of you array containing the arrays than accessing values in an array containing integers. The only difference is that what you get if you retrieve a value from your array, is another array. That array can you then in turn access values from just like a normal array to.
You can do all of this in "one" line if you'd like. For example
echo $array[1]["user_info"]["name"]
which would print Josh
But what actually happens is no magic.
You retrieve the element at index 1 from your array. This happens to be an array so you retrieve the element at index *user_info* from that. What you get back is also an array so you retrieve the element at index name.
So this is the same as doing
$arrayElement = $array[1];
$userInfo = $arrayElement["user_info"];
$name = $userInfo["name"];
Although this is "easier" to read and debug, the amount of code it produces sometimes makes people write the more compact version.
Since you get an array back you can also do things like iterating you array with a foreach loop and within that loop iterate each array you get from each index within the first array. This can be a quick way to iterate over multidimensional array and printing or doing some action on each element in the entire structure.
I've got an array like this
Array
(
[0] => Array
(
[0] => Array
(
[szam] => 8
[index] => 0
)
)
[1] => Array
(
[0] => Array
(
[szam] => 1
[index] => 0
)
[1] => Array
(
[szam] => 7
[index] => 1
)
)
I thought that my last cmp will work fine
function maxSzerintCsokkeno($item1,$item2)
{
if ($item1['szam'] == $item2['szam']) return 0;
return ($item1['szam'] < $item2['szam']) ? 1 : -1;
}
with foreach
foreach ($tomb as $kulcs => $adat) usort($adat,"maxSzerintCsokkeno");
but it dosen't do anything, advise?
foreach ($tomb as $kulcs => $adat) usort($adat,"maxSzerintCsokkeno");
This only sorts the subarray array $adat. And this only exists temporarily until foreach loops over the next one. The lazy option here would be to use a reference:
foreach ($tomb as & $adat) usort($adat,"maxSzerintCsokkeno");
Notice the &. This way the modification on $adat will be applied directly in the parent array.
You're sorting a temporary variable, meaning the changes are not applied. The following should work for you:
for($i = 0, $length = count($tomb); $i < $length; $i++)
{
usort($tomb[$i], "maxSzerintCsokkeno");
}
When iterating through the foreach loop, the key and value variables ($kulcs and $adat in your code) are copies of the actual values in the array. Like Tim Cooper said, you are actually sorting a copy of the original value.
You can also pass the value by reference in your foreach loop. This means that you will be modifying the original value:
foreach ($tomb as $kulcs => &$adat) usort($adat,"maxSzerintCsokkeno");
I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.
I have an array that looks like the one below. I'm trying to group and count them, but haven't been able to get it to work.
The original $result array looks like this:
Array
(
[sku] => Array
(
[0] => 344
[1] => 344
[2] => 164
)
[cpk] => Array
(
[0] => d456
[1] => d456
)
)
I'm trying to take this and create a new array:
$item[sku][344] = 2;
$item[sku][164] = 1;
$item[cpk][d456] = 1;
I've gone through various iterations of in_array statements inside for loops, but still haven't been able to get it working. Can anyone help?
I wouldn't use in_array() personally here.
This just loops through creating the array as it goes.
It seems to work without needing to first set the index as 0.
$newArray = array();
foreach($result as $key => $group) {
foreach($group as $member) {
$newArray[$key][$member]++;
}
}