I have an array of values, and i want to insert the values to another array but with an if condition, if the "if" is true I want to skip the iteration.
Code:
$array=array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
$insert=array();
foreach($array as $k1=>$v1)
{
foreach($v1 as $k2=>$v2)
{
if($v2==23)
{
break;
}
}
$insert[]=$v1;
}
final result should look like that
Array
(
[0] => Array
(
[1] => 11
[2] => 22
[3] => 44
[4] => 55
)
)
I tried using: break,return,continue...
Thanks
There are a few ways to do this. You can loop over the outer array and use array_filter on the inner array to remove where the value is 23 like this (IMO preferred; this also uses an array of $dontWant numbers so it is easier to add or change numbers later):
<?php
$array = array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
$insert = array();
//array of numbers you don't want
$dontWant = array(23);
//loop over outer array
foreach($array as $subArray){
//add to $insert a filtered array
//subArray is filtered to remove where value is in $dontWant
$insert[] = array_filter($subArray, function($val) uses ($dontWant) {
//returns true if the value is not in the array of numbers we dont want
return !in_array($val, $dontWant);
});
}
//display final array
echo '<pre>'.print_r($insert,1).'</pre>';
Or you can reference the first key to add to a sub array in $insert like (which is a little more like what your code is trying to do and show that you are not too far off):
<?php
$array = array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
$insert = array();
//loop over outer array
foreach($array as $k1=>$v1){
//add an empty array to $insert
$insert[$k1] = array();
//loop over inner array
foreach($v1 as $k2=>$v2){
//if the inner array value is not 23
if($v2 != 23){
//add to inner array in insert
$insert[$k1][] = $v2;
}
}
}
//display the result
echo '<pre>'.print_r($insert,1).'</pre>';
Both of these methods would produce the same result. IMO using array_filter is the preferred method, but the second method might be a little easier to understand for someone new to programming.
Why don't you just try it like this?
foreach($v1 as $k2=>$v2)
{
if($v2!=23)
{
$insert[]=$v2;
}
}
EDIT:
Explanation: You check with the if($v2!=23) if the value of the variable $v2 is not equal to (that is the != sign) any given number that stands after the inequality operator, and if so, it will insert that value to the array $insert.
I hope it is clear now.
Sorry, I've written $v1 instead of $v2, the code should work now.
To add variants :)
$array=array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
$insert=array();
foreach($array as $a)
{
while (($i = array_search(23, $a)) !== false)
{ unset($a[$i]); sort($a); }
$insert[] = $a;
}
print_r($a);
result:
Array ( [0] => Array ( [0] => 11 [1] => 22 [2] => 44 [3] => 55 ) )
Related
I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:
Array
(
[0] => Array
(
[key] => 31
[field] => CONSTRUCTN
[value] => LFD_CONSTRUCTION_2
)
[1] => Array
(
[key] => 32
[field] => COOLING
value] => LFD_COOLING_1
)
)
I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".
I've tried using array_search(31, $myArray) but it does not work...
function searchMultiArray($val, $array) {
foreach ($array as $element) {
if ($element['key'] == $val) {
return $element['field'];
}
}
return null;
}
And then:
searchMultiArray(31, $myArray);
Should return "CONSTRUCTN".
One-line solution using array_column and array_search functions:
$result = array_search(31, array_column($arr, 'key', 'field'));
print_r($result); // CONSTRUCTN
Or with simple foreach loop:
$search_key = 31;
$result = "";
foreach ($arr as $item) { // $arr is your initial array
if ($item['key'] == $search_key) {
$result = $item['field'];
break;
}
}
print_r($result); // CONSTRUCTN
I haven't tested, but I think this should do it.
function searchByKey($value, $Array){
foreach ($Array as $innerArray) {
if ($innerArray['key'] == $value) {
return $innerArray['field'];
}
}
}
Then calling searchByKey(31, $myArray); should return 'CONSTRUCTN'.
One liner solution:
$result = is_numeric($res = array_search(31, array_column($myArray, 'key'))) ? $myArray[$res]["field"] : "";
array_search accepts 2 parameters i.e the value to be search and the array, subsequently I've provided the array which needs searching using array_column which gets that particular column from the array to be searched and is_numeric is used to make sure that valid key is returned so that result can displayed accordingly.
I want to check two arrays that contain similar elements. If the element in the second array containing the same element inside the first array, then save it and ignore everything after it that contain that element. And if any element in the second array is not an element of the first array and not contain any element in the first array, then save it too.
It basically is like this:
$array_1 = Array(
[0] => car,
[1] => bike,
[2] => plane,
[3] => ship
);
$array2 = Array(
[0] => tiger_claws,
[1] => bike,
[2] => bike_1,
[3] => bike_30,
[4] => bike_clone,
[5] => bike_sold,
[6] => plane,
[7] => plane_3a,
[8] => plane_fly
);
From the array examples above, I want to take tiger_claws bike and plane into new separated array that will be named $new_array. The actual data I processed is dynamic, so I need a dynamic approach too.
Here is my try to achieve it:
$count = count($array2);
$new_array = array();
for($i=0; $i<$count; $i++ ) {
foreach($array_1 as $arr){
if ($array2[$i] == $arr) {
$new_array[] = $arr;
if (strpos($array2[$i], $arr)){
continue;
}
} elseif (strpos($array2[$i], $arr) === false){
$new_array[] = $arr;
}
}
}
How do I catches the tiger_claws, bike and plane only and then put them into $new_array and leave everything else?
EDIT:
The $array2 may sometimes contain one or more elements that have underscore and that element not containing any string/ element in $array_1.
This thing is very complicated for me. Hope somebody would like to give the correct logic!
Best Regards
$new_array();
foreach ($array2 as $string) {
if (!in_array($string, $array1) &&
!in_array($string, $new_array) &&
!strpos($string, '_')) {
$new_array[] = $string;
}
}
This code loops through $array2 and checks:
if the current array value is in $array1 (if so, ignore it)
if the current array value is already in $new_array (if so, ignore it)
if the underscore '_' is not present in the current array
If so, it is added to $new_array.
Here is the solution I found. Hope someone can benefit from this answer! Please suggest me the more elegant solution if you have it.
First, we check if there are any element of $array_1 that is contained in $array2 and collect them to a new array if there is matched element:
$check = array();
foreach(array2 as $arr){
foreach($array_1 as $arr1){
if($arr == $arr1) {
$check[] = $arr;
}
}
}
Next, do the filtering with the new array created above and save the elements we want into $new_array
$new_array = array();
foreach(array2 as $arr){
foreach($check as $chk){
if($arr == $chk || strpos($arr, $chk) === false) {
$new_array[] = $arr;
}
}
}
Now, the $new_array elements will be:
tiger_claws,
bike,
plane
About strpos. According to my test and the reference here, !strpos($var1, $var2) is not the correct opposite of strpos($var1, $var2). This is an example of the correct way to test if strpos is false:
if(strpos($var1, $var2) === false) {
// do your stuff
}
Not sure why I can't this to work. My json is:
[values] => Array
(
[0] => Array
(
[field] => id1
[value] => 985
)
[1] => Array
(
[field] => id2
[value] => 6395
)
[2] => Array
(
[field] => memo
[value] => abcde
)
I simply want the values of id2
I tried:
foreach ($json['values'] as $values) {
foreach ($json as $key=>$data) {
if ($data['field'] == 'id2') {
$result = $data['value'];
print '<br>value: '.$result;
}
}
}
Thanks. I know this should be relatively simple and I'm sure I've done this correctly before.
there's no need for inner loop, after the first one $values already contain the exact array that you are looking for
foreach ($json['values'] as $values) // $values contain
{
if ($values['field'] == 'id2')
{
$result = $values['value'];
print '<br>value: '.$result;
}
}
foreach ($json['values'] as $values) { //you're looping your first array, puttin each row in a variable $values
foreach ($values as $key=>$data) { //you're looping inside values taking the array index $key and the value inside that index $data
if ($key == 'id2') { //test if $key (index) is = to id2
print '<br>value: '.$value; // print the value inside that index
}
}
}
this is just an explanation, to what is going wrong with your code, but as #Pawel_W there is no need for the second foreach loop you can directly test
if($values['field']=='id2'){ print $values['value'];}
I think you just need to use array_search.
And here is recursive array_search ;
Assuming there might be multiple fields with the same name and you want them all as array, here's an alternative take:
array_filter(array_map(function($item) { return $item['field'] == 'id2' ? $item['value'] : null; }, $json['values']));
If your field names are always unique and you just want a single scalar:
array_reduce($json['values'], function($current, $item) { return $item['field'] == 'id2' ? $item['value'] : $current; });
(note that this one is not ideal since it will walk all the array even if match is found in first element)
And here's a gist with both in this and function form + output.
I am writing a script to compare the achievements of one player to another in a game. In each of the arrays the id and timestamp will match up on some entries. I have included a sample of one of the start of the 2 separate arrays:
Array
(
[0] => Array
(
[id] => 8213
[timestamp] => 1384420404000
[url] => http://www.wowhead.com/achievement=8213&who=Azramon&when=1384420404000
[name] => Friends In Places Higher Yet
)
[1] => Array
(
[id] => 6460
[timestamp] => 1384156380000
[url] => http://www.wowhead.com/achievement=6460&who=Azramon&when=1384156380000
[name] => Hydrophobia
)
I want to find all of the array items where the id and timestamp match. I have looked into array_intersect but I don't think this is what I am looking for as it will only find items when the entries are identical. Any help much appreciated.
You may use array_intersect_assoc function.
Try something like this:
<?php
$key_match = Array();
//Loop first array
foreach($array as $key => $element){
//Compare to second array
if($element == $array2[$key]){
//Store matching keys
$key_match[] = $key;
}
}
?>
$key_match will be an array with all matching keys.
(I'm at work and havn't had time to test the code)
Hope it helps
EDIT:
Fully working example below:
<?php
$a1["t"] = "123";
$a1["b"] = "124";
$a1["3"] = "125";
$a2["t"] = "123";
$a2["b"] = "124";
$a2["3"] = "115";
$key_match = Array();
//Loop first array
foreach($a1 as $key => $element){
//Compare to second array
if($element == $a2[$key]){
//Store matching keys
$key_match[] = $key;
}
}
var_dump($key_match);
?>
If you want to go on an exploration of array callback functions, take a look at array_uintersect. It's like array_intersect except you specify a function to use for the comparison. This means you can write your own.
Unfortunately, you need to implement a function that returns -1, 0 or 1 based on less than, same as, greater than, so you need more code. But I suspect that it'll be the most efficient way of doing what you're looking for.
function compareArrays( $compareArray1, $compareArray2 ) {
if ( $compareArray1['id'] == $compareArray2['id'] && $compareArray1['timestamp'] == $compareArray2['timestamp'] ) {
return 0;
}
if ( $compareArray1['id'] < $compareArray2['id'] ) {
return -1;
}
if ( $compareArray1['id'] > $compareArray2['id'] ) {
return 1;
}
if ( $compareArray1['timestamp'] < $compareArray2['timestamp'] ) {
return -1;
}
if ( $compareArray1['timestamp'] > $compareArray2['timestamp'] ) {
return 1;
}
}
var_dump( array_uintersect( $array1, $array2, "compareArrays") );
I have 2 Arrays :
Array
(
[1] => image1
[4] => image2
)
Array
(
[0] => title 1
[2] => title 2
[3] => title 3
)
I just want to merge these arrays and KEEP their key ([1] => image1 will also be at [1] in the new array)
Any idea please ? Thanks !
That should work :)
foreach ($array2 as $key => $value)
{
$array1[$key] = $value;
}
The keys & values from array2 will be appended at the end. If your array is just numeric, you can bring it to the right order with array_sort().
I think this function works. You have to use only numeric keys tough
$array1;
$array2;
array_weird_merge($array1, $array2){
$result = array();
//get the keys of each array
$keys1 = array_keys($array1);
$kesy2 = array_keys($array2);
//get the max keys of the 2 arrays
$max = max($key1, $key2);
//we go trough all the possible values
for ($i=0; $i<$max;$i++){
//if the array 1 has an element in the
//$i position, we put it in the result
//if not, then we check in the second
//array. (we give priority to the array
//that comes first)
if(isset($array1[$i])){
$result[$i] = $array1[$i];
}else if(isset($array2[$i])){
$result[$i] = $array2[$i];
}
}
return $result;
}