Read through loop and find PHP - php

I have an array like:-
([0] =>Array([amount] => 1, [address]=> 'a'),
[1] =>Array([amount] => 12, [address]=> 'b'),
[2] =>Array([amount] => -1, [address]=> 'a'),
[3] =>Array([amount] => 3, [address]=> 'a'))
How do I make an Loop so that at last I get amounts of a and only positive ones.

Let's say your array is this,
$array = array(
array('amount' => 3, 'address' => 'a'),
array('amount' => 26, 'address' => 'a'),
array('amount' => 345, 'address' => 'a'),
array('amount' => -3, 'address' => 'a'),
array('amount' => 22, 'address' => 'a'),
);
You can write a small for loop to achieve this,
$results = array();
foreach ($array as $k => $v){
if($v['amount'] > 0 && $v['address'] == 'a'){
$results[] = $v;
}
}
print_r($results);
This will give you elements where amount is greater than 0 and address is a. Is this what you looking for?

Could you be more precise with what you want ?
Assuming that your array is in an var called $_var
foreach($_var as $_array){
if($_array['amount'] > 0 && $_array['address']=='a'){ //if the amount is positiv and address = 'a'
$res[] = $_array; //Push the current item in your res array
}
}
$amount_of_a = count($res); //The number of a
print_r($res); //your result

Related

Offset by number in an array

I just can't figure it out, there is a code like this:
$a1 = ['k1' => '1', 'k2' => '2','k3' => '3', 'k4' => '4', 'k5' => '5'];
$a2 = ['k1' => '-1', 'k2' => '-2','k3' => '-3', 'k4' => '-4', 'k5' => '-5'];
$ix = 1; // number to move to
$k = 'k3'; // the key we want to move
$i = 1; // iteration number
$oldk1 = $oldk2 = '';
foreach($a1 as $key => $value) {
if($k === $key && $ix != $i) {
$oldk1 = $value;
$oldk2 = $a2[$k];
unset($a1[$k], $a2[$k]);
}
if($i === $ix) {
$a1[$k] = $oldk1;
$a2[$k] = $oldk2;
}
++$i;
}
But it does not work, why I cannot understand what I was trying to do, I cannot solve this problem.
It consists in the following:
2 arrays with the same keys, but with different values, they must always go through the keys in the same order.
How to make it so that when I want, for example, that k3 stands in 1 place or on any other, I enter a number from 1 to the maximum in the array and so that in 2 arrays it is rearranged to the specified number and so that it is already like this:
$a1 = ['k3' => '3', 'k1' => '1', 'k2' => '2', 'k4' => '4', 'k5' => '5'];
$a2 = ['k3' => '-3', 'k1' => '-1', 'k2' => '-2', 'k4' => '-4', 'k5' => '-5'];
Moving an array element by key to a new position. Here the index of the first element in the array starts at 1 as described in the question.
$a1 = ['k1' => '1', 'k2' => '2','k3' => '3', 'k4' => '4', 'k5' => '5'];
$a2 = ['k1' => '-1', 'k2' => '-2','k3' => '-3', 'k4' => '-4', 'k5' => '-5'];
$k = 'k3'; // Key to move
$i = 1; // New position index
// Retrieve the element with key $k
$element = array_splice($a1, array_flip(array_keys($a1))[$k], 1);
// Insert an element at a new position
$a1 = array_merge(
array_slice($a1, 0, $i - 1),
$element,
array_slice($a1, $i - 1)
);
// Rearrange $a2 keys and values by $a1 array
$a2 = array_merge($a1, $a2);
print_r($a1);
print_r($a2);

Merge column values from two arrays to form an indexed array of associative arrays

I have two arrays:
$a = ['0' => 1, '1' => 2, '2' => 3]
$b = ['0' => 4, '1' => 5, '2' => 6]
I want to create a new array like this:
[
['a' => 1, 'b' => '4'],
['a' => '2', 'b' => '5']
]
I have tried using array_merge and array_merge_recursive, but I wasn't able to get the right results.
$data = array_merge_recursive(array_values($urls), array_values($id));
You have to apply array_map() with custom function:
$newArray = array_map('combine',array_map(null, $a, $b));
function combine($n){
return array_combine(array('a','b'),$n);
}
print_r($newArray);
Output:-https://3v4l.org/okML7
Try this one
$c = array_merge($a,$b)
$d[] = array_reduce($d, 'array_merge', []);
It will merge the two array and reduce and remerge it.
You can use foreach to approach this
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$res = [];
$i = 0;
$total = 2;
foreach($a as $k => $v){
$res[$i]['a'] = $v;
$res[$i]['b'] = $b[$k];
$i++;
if($i == $total) break;
}
The idea is to have an array $ab = ['a','b'] and a array from your both arrays like this $merged_array = [[1,4],[2,5],[3,6]]. Now we can combine array $ab with each element of $merged_array and that will be the result we need.
$first = ['0' => 1, '1' => 2, '2' => 3];
$second = ['0' => 4, '1' => 5, '2' => 6];
$merged_array = [];
for($i=0;$i<count($first);$i++)
{
array_push($merged_array,[$first[$i],$second[$i]]);
}
$final = [];
$ab = ['a','b'];
foreach($merged_array as $arr)
{
array_push($final,array_combine($ab, $arr));
}
print_r($final);
All earlier answers are working too hard. I see excessive iterations, iterated function calls, and counter variables.
Because there are only two arrays and the keys between the two arrays are identical, a simple foreach loop will suffice. Just push associative arrays into the result array.
Code: (Demo)
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$result = [];
foreach ($a as $k => $v) {
$result[] = ['a' => $v, 'b' => $b[$k]];
}
var_export($result);
Output:
array (
0 =>
array (
'a' => 1,
'b' => 4,
),
1 =>
array (
'a' => 2,
'b' => 5,
),
2 =>
array (
'a' => 3,
'b' => 6,
),
)

php merge multiple array elements remain the same, an array of different elements

Help:
Array format like this:
$arr=array(
array('element1'=>'a','element2'=>1),
array('element1'=>'b','element2'=>2),
array('element1'=>'a','element2'=>2),
array('element1'=>'b','element2'=>3),
);
Synthesis is needed,how to change it like:
$arr=array(
array('element1'=>'a','element2'=>array(1,2)),
array('element1'=>'b','element2'=>array(2,3)),
);
$new = array();
foreach ($arr as $key => $value) {
$new[$value['element1']][] = $value['element2'];
}
$new2 = array();
foreach($new as $k=>$v){
$new2[] = array('element1'=>$k,'element2'=>$v);
}
print_r($new2);
Result
array(
array('element1' => 'a', 'element2' => array(0 => 1, 1 => 2)),
array('element1' => 'b', 'element2' => array(0 => 2, 1 => 3)),
)

php custom array_replace_recursive method

I need a custom array_replace_recursive($array, $array1) method which does what the original array_replace_recursive($array, $array1) method does except that for indexed array it should use the array in the second array and overwrite the first array recursively.
example:
$a = array (
'a' => array(1,2,3),
'b' => array('a' => 1, 'b' => 2, 'c' => 3)
);
$b = array (
'a' => array(4),
'b' => array('d' => 1, 'e' => 2, 'f' => 3)
);
$c = array_replace_recursive($a, $b);
current behaviour:
$c = array (
'a' => array(4,2,3),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 1, 'e' => 2, 'f' => 3)
);
desired behaviour:
$c = array (
'a' => array(4),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 1, 'e' => 2, 'f' => 3)
);
as you can see element 'a' is an indexed array so the element in the second array has overwritten the element in the first array. element 'b' is an associative array so it maintains the original behaviour.
Below worked for me:
<?php
/**
* This method finds all the index arrays in array2 and replaces array in array1. it checks for indexed arrays recursively only within associative arrays.
* #param $array1
* #param $array2
*/
function customMerge(&$array1, &$array2) {
foreach ($array2 as $key => $val) {
if(is_array($val)) {
if(!isAssoc($val)) {
if($array1[$key] != $val) {
$array1[$key] = $val;
}
} else {
$array1_ = &$array1[$key];
$array2_ = &$array2[$key];
customMerge($array1_, $array2_);
}
}
}
}
function isAssoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
$a = array (
'a' => array(1,2,3),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'g' => array(
4,5,6
))
);
$b = array (
'a' => array(4),
'b' => array('d' => 1, 'e' => 2, 'f' => 3, 'g' => array(
7
))
);
$c = array_replace_recursive($a, $b); // first apply the original method
$expected = array (
'a' => array(4),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 1, 'e' => 2, 'f' => 3, 'g'=> array(
7
)),
);
$d = $c; // create copy
customMerge($d, $b); // do the custom merge
echo $d == $expected;
The isAssoc() method in the first answer of this post is what your looking for:
How to check if PHP array is associative or sequential?
That method will check if the array is index and return true if it's the case.

php - sort an array by key to match another array's order by key

I have two arrays, both have the same keys (different values) however array #2 is in a different order. I want to be able to resort the second array so it is in the same order as the first array.
Is there a function that can quickly do this?
I can't think of any off the top of my head, but if the keys are the same across both arrays then why not just loop over the first one and use its key order to create a new array using the the values from the 2nd one?
$arr1 = array(
'a' => '42',
'b' => '551',
'c' => '512',
'd' => 'gge',
) ;
$arr2 = array(
'd' => 'ordered',
'b' => 'is',
'c' => 'now',
'a' => 'this',
) ;
$arr2ordered = array() ;
foreach (array_keys($arr1) as $key) {
$arr2ordered[$key] = $arr2[$key] ;
}
You can use array_replace
$arr1 = [
'x' => '42',
'y' => '551',
'a' => '512',
'b' => 'gge',
];
$arr2 = [
'a' => 'ordered',
'x' => 'this',
'y' => 'is',
'b' => 'now',
];
$arr2 = array_replace($arr1, $arr2);
$arr2 is now
[
'x' => this,
'y' => is,
'a' => ordered,
'b' => now,
]
foreach(array_keys($array1) as $key)
{
$tempArray[$key] = $array2[$key];
}
$array2 = $tempArray;
I am not completely sure if this is what your after. anyways as long as the the array remains the same size, than this should work for you.
$gamey = array ("wow" => "World of Warcraft", "gw2" => "Guild Wars2", "wiz101" => "Wizard 101");
$gamex = array ("gw2" => "best game", "wiz101" => "WTF?", "wow" => "World greatest");
function match_arrayKeys ($x, $y)
{
$keys = array_keys ($x);
$values = array_values ($y);
for ($x = 0; $x < count ($keys); $x++)
{
$newarray [$keys[$x]] = $y[$keys[$x]];
}
return $newarray;
}
print_r (match_arrayKeys ($gamey, $gamex));
Output
[wow] => World greatest
[gw2] => best game
[wiz101] => WTF?
Try this
CODE
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
OUTPUT
a = orange
b = banana
c = apple
d = lemon
Check the php manual for ksort()

Categories