I'm trying to to update the value of array one, if it is found within array two, e.g:
$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish'];
I need to get the data back as:
$has_pets = ['Cat' => 1, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 1];
I've tried playing with the array_intersect() function and a foreach loop but for the life of me I could not get it working.
Cheers in advance
You can use array_merge() and array_count_values():
array_merge($all_pets, array_count_values($user_has));
Here's a demo
array_count_values() counts the occurrences of each value in the array, and returns an array with value => count pairs.
array_merge() merges the arrays, if they have the same string keys, then the later value for that key will overwrite the previous one.
You can use foreach to loop thru the array $user_has. Use isset() to check if the key exist in $all_pets. If it does, change the value.
$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish'];
foreach( $user_has as $value ) {
if ( isset( $all_pets[ $value ] ) ) $all_pets[ $value ]++;
}
This will result to:
Array
(
[Cat] => 1
[Dog] => 0
[Bird] => 0
[Rabbit] => 0
[Fish] => 1
)
<?php
$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish'];
$has_pets = array();
foreach ($user_has as $key => $pet) {
$has_pets[$pet]++;
}
print_r(array_merge($all_pets, $has_pets));
?>
Use foreach and in_array()
$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish'];
foreach($all_pets as $key=>$value){
if(in_array($key,$user_has){
$indexes = array_keys($user_has,$key);
$all_pets[$key]= count($indexes);
}
}
Related
I have several arrays that all have this structure:
array (
526744 =>
array (
'completed' => 13,
'total' => 24,
'topics' =>
array (
),
'lessons' =>
array (
526745 => 1,
526747 => 1,
526749 => 1,
526751 => 0,
526757 => 0,
526759 => 0,
526761 => 1,
526763 => 0,
526765 => 0,
526767 => 1,
),
'last_id' => 526793,
),
526818 =>
array (
'completed' => 0,
'total' => 22,
'topics' =>
array (
),
'lessons' =>
array (
526819 => 0,
526821 => 1,
526823 => 1,
526845 => 0,
526847 => 1,
526849 => 1,
526859 => 1,
526861 => 1,
),
'last_id' => 526861,
),
)
The number in the outer-most element of the array is a course id. The list of numbers in the inner-most array elements are lesson ids.
I want to merge all of the arrays that contain this structure together. But only ones with the course id of 526744.
If I do something like this:
foreach($results2 as $result2) {
$new_array = unserialize($result2->course_progress);
$final_array = array_merge($final_array, $new_array);
$backup_array = $new_array;
}
This works fine, but it merges the entire arrays, including all courses.
However if I specify the course_id like this:
foreach($results2 as $result2) {
$new_array = unserialize($result2->course_progress);
$newarray = $new_array[526744];
$final_array = array_merge($final_array, $new_array);
$backup_array = $new_array;
}
It no longer merges at all and just lists out the last array for that 1 single course specified.
Any ideas on what is causing this and how to fix it?
Thanks
I have check your code and found the issue, you have used $new_array[526744] which is wrong. it should be array($new_array[526744])
Check this code:
foreach($results2 as $result2) {
$new_array = unserialize($result2->course_progress);
$newarray = array($new_array[526744]);
$final_array = array_merge($final_array, $new_array);
$backup_array = $new_array;
}
I have the following multidimensional array. I had to create keys the way it looks to group them accordingly.
Array
(
[Oranges] => Array
(
[Name] => Oranges
[l.VA123] => 17
[l.MA123] => 12
[l.GA123] => 9
[l.CT123] => 5
)
[Apple] => Array
(
[Name] => Apple
[l.CA123] => 13
)
[Grapes] => Array
(
[Name] => Grapes
[l.WI123] => 8
[l.FL123] => 5
)
)
However, I need all the subarrays to have the same keys. Missing ones should be filled with a value of 0. The final array should be like below so that all subarrays have equal length.
Array
(
[Oranges] => Array
(
[Name] => Oranges
[l.VA123] => 17
[l.MA123] => 12
[l.GA123] => 9
[l.CT123] => 5
[l.CA123] => 0
[l.WI123] => 0
[l.FL123] => 0
)
[Apple] => Array
(
[Name] => Apple
[l.CA123] => 13
[l.WI123] => 0
[l.FL123] => 0
[l.VA123] => 0
[l.MA123] => 0
[l.GA123] => 0
[l.CT123] => 0
)
[Grapes] => Array
(
[Name] => Grapes
[l.WI123] => 8
[l.FL123] => 5
[l.CA123] => 0
[l.VA123] => 0
[l.MA123] => 0
[l.GA123] => 0
[l.CT123] => 0
)
)
You need a simple + operator. As from manual:
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
$items = Array
(
'Oranges' => Array
(
'Name' => 'Oranges',
'l.VA123' => 17,
'l.MA123' => 12,
'l.GA123' => 9,
'l.CT123' => 5,
),
'Apple' => Array
(
'Name' => 'Apple',
'l.CA123' => 13,
),
'Grapes' => Array
(
'Name' => 'Grapes',
'l.WI123' => 8,
'l.FL123' => 5,
),
);
// static keys
$keys = [
'l.VA123' => 0,
'l.MA123' => 0,
'l.GA123' => 0,
'l.CT123' => 0,
'l.CA123' => 0,
'l.WI123' => 0,
'l.FL123' => 0,
];
// keys generated from source array, tricky approach
$keys = array_fill_keys(
// here we merge all elements of `$items` into one array
// as keys are repeated - you definitely got all keys that
// can be in `$items`, `array_keys` will give you these keys
// `array_fill_keys` will create array where key is what you need
// and value is 0.
array_keys(call_user_func_array('array_merge', $items)),
0
);
// keys generated from source array, SIMPLE approach
$keys = [];
foreach ($items as $item) {
foreach ($item as $k => $v) {
if ($k != 'Name') {
$keys[$k] = 0;
}
}
}
foreach ($items as &$item) {
$item = $item + $keys;
}
print_r($items);
Probably someone can come up with something more efficient, but without a list of keys that you want, I think you'll need to take a couple of passes of the array:
<?php
$fruits = [
"Oranges"=>["Name"=>"Oranges", "l.VA123"=>17, "l.MA123"=>12, "1.GA123"=>9, "1.CT123"=>5],
"Apple"=>["Name"=>"Apple", "1.CA123"=>13],
"Grapes"=>["Name"=>"Grapes", "1.WI123"=>8, "1.FL123"=>5]
];
$keys = [];
foreach ($fruits as $fruit) {
unset($fruit["Name"]);
$keys = array_merge($keys, array_keys($fruit));
}
$keys = array_fill_keys(array_unique($keys), 0);
foreach ($fruits as &$fruit) {
$fruit = array_merge($keys, $fruit);
}
print_r($fruits);
Since all keys and default values are "known", create an associative array, use a foreach() and modify the rows by reference, and use the union-assignment (combined) operator. This will allow the original values to overwrite the default values.
Code: (Demo)
$keys = [
'l.VA123' => 0,
'l.MA123' => 0,
'l.GA123' => 0,
'l.CT123' => 0,
'l.CA123' => 0,
'l.WI123' => 0,
'l.FL123' => 0,
];
foreach ($items as &$row) {
$row += $keys;
}
var_export($items);
If you want the keys to be consistently positioned, then use array_replace() or array_merge() instead of the union assignment operator.
Code: (Demo)
foreach ($items as &$row) {
$row = array_replace($keys, $row);
}
i have foreach loop that returns multi-array from the database
and i want to convert this array to multi array in json ,
how to do this ?
php array example
Array
(
[0] => Array
(
[it_code] => 2894
[it_quantity] => 300
[it_price] => 0
[it_notes] =>
)
[1] => Array
(
[it_code] => 2894
[it_quantity] => 284
[it_price] => 0
[it_notes] =>
)
[2] => Array
(
[it_code] => 2894
[it_quantity] => 4
[it_price] => 0
[it_notes] =>
)
[3] => Array
(
[it_code] => 2894
[it_quantity] => 3
[it_price] => 0
[it_notes] =>
)
)
i want returned json to be like this format
[
['2894', 300, 0,''],
['2894', 284, 0,''],
['2894', 4, 0,''],
['2894', 3, 0,''],
['2894', 10, 0, '']
]
my code like this
$this->db->where("it_parent_item", $parent_id);
$this->db->select("d_items.it_code,d_items_type.it_ty_ar_desc,d_items.it_quantity,d_items.it_price,it_notes");
$this->db->join('d_items_type','d_items_type.it_ty_id=d_items.it_type','left');
$this->db->from("d_items");
$result = $this->db->get()->result_array();
echo "<pre>";
print_r($result);
echo "</pre>";
You can use array_values() and array_walk_recursive() to convert integer to string
$newArray = array();
foreach($sourceArray as $element) {
$newArray[] = array_values($element);
}
array_walk_recursive($newArray,
function(&$value, $key){
$value = (string)$value;
});
print_r (json_encode($newArray));
Note that other answers will give null instead of ''.
So, without using array_values, this code returns all values, but in case there is any null, it returns '' instead (as expected in the question):
$arr = array();
foreach($foo as $value){
$tmp = array();
foreach($value as $v){
$tmp[] = $v===null ? '' : $v;
}
$arr[] = $tmp;
}
echo json_encode($arr);
Output:
[[2894,300,0,""],[2894,284,0,""],[2894,4,0,""],[2894,3,0,""]]
[
[2894,300,0,""],
[2894,284,0,""],
[2894,4,0,""],
[2894,3,0,""]
]
This a copyable array:
$foo = array
(
0 => array
(
'it_code' => 2894,
'it_quantity' => 300,
'it_price' => 0,
'it_notes' => null
),
1 => Array
(
'it_code' => 2894,
'it_quantity' => 284,
'it_price' => 0,
'it_notes' => null
),
2 => Array
(
'it_code' => 2894,
'it_quantity' => 4,
'it_price' => 0,
'it_notes' => null
),
3 => Array
(
'it_code' => 2894,
'it_quantity' => 3,
'it_price' => 0,
'it_notes' => null
),
);
Here's the initial array (shown like a PHP array, but the same as your post):
$initialArray = array(
array(
"it_code" => 2894,
"it_quantity" => 300,
"it_price" => 0,
"it_notes" => '',
),
array(
"it_code" => 2894,
"it_quantity" => 284,
"it_price" => 0,
"it_notes" => '',
),
array(
"it_code" => 2894,
"it_quantity" => 4,
"it_price" => 0,
"it_notes" => '',
),
array(
"it_code" => 2894,
"it_quantity" => 3,
"it_price" => 0,
"it_notes" => '',
),
);
You can loop over each element, assigning just the values to a new set of arrays, like this:
$newArray = array();
foreach ($initialArray as $subArray)
{
$newArray[] = array_values($subArray);
}
The resulting array will look like this:
[[2894,300,0,""],[2894,284,0,""],[2894,4,0,""],[2894,3,0,""]]
Looks to me like you want to loop through your array so it's formatted how you want in PHP and then convert that PHP array into JSON:
$dataArray = array(); //The array containing your values
$jsonArray = array(); //The array which will be formatted for json
foreach($dataArray as $value){
$keylessValues = array_values($value);
$jsonArray[] = $keylessValues;
}
$jsonArray = json_encode($jsonArray); //This is now a JSON array storing your values
What we do here is move through the array and then take only the values with array_values() and put them into a new index in our $jsonArray.
Once we have moved through the entire array we can convert our newly formatted and populated array into JSON with json_encode()
It's worth noting that your values that are set as '' will come through as null. If you need those values as '' instead of null have a look at the answer #FirstOne gave.
I have array in php :
Array
(
[id] => 1
[comp_id] => 1
[transaction_purpose] => 0
[source_of_funds] => 1
[beneficiary_relationship] => 0
[cus_occupation] => 0
[cus_id_image_2] => 0
[cus_id_image_3] => 0
[ben_id_type] => 0
[ben_id_number] => 1
)
I want to get only array key=>value pair if the valie is 1.
result array should be:
Array
(
[id] => 1
[comp_id] => 1
[source_of_funds] => 1
[ben_id_number] => 1
)
I tried with:
$returnArray = array();
foreach($mainArray as $r){
if($r>0){
array_push($returnArray, $mainArray);
}
}
But, It's giving me 4 times main array. Is there any way to achieve this? Thanks..
Just use array_filter():
$newarray = array_filter($array, function($var) {
return ($var === 1);
});
$newarray = array_filter($array);
Demo
$array = array(
'id' => 1,
'comp_id' => 1,
'transaction_purpose' => 0,
'source_of_funds' => 1,
'beneficiary_relationship' => 0,
'cus_occupation' => 0,
'cus_id_image_2' => 0,
'cus_id_image_3' => 0,
'ben_id_type' => 0,
'ben_id_number' => 1
);
$newarray = array_filter($array);
print_r($newarray);
Array
(
[id] => 1
[comp_id] => 1
[source_of_funds] => 1
[ben_id_number] => 1
)
Try this:
$returnArray = array_filter($result);
You can see PHP's array_filter function for more info.
Well, what else are you expecting to happen?
array_push($returnArray, $mainArray);
If you find an element which has >0 value, you push the ENTIRE original array onto the new one, not just the key/value you just tested.
You probably want:
$newarr = array();
foreach($mainArray as $key => $value) {
if ($value > 0) {
$newarr[$key] = $value;
}
}
I have 1 array that has the right values that I need but it is out of order. I then have another array with the same keys and it is in the right order but the values are not what I need.
Here is my first array with the correct values but is out of order:
Array
(
[countTotal] => 7268
[zip] =>
[yearName] =>
[countZipRadius] =>
[Acura] => 1334
[Cadillac] => 511
[Ford] => 5423
)
Here is my second array with the right order but the wrong values:
Array
(
[countZipRadius] => 0
[zip] => 1
[yearName] => 2
[Acura] => 3
[Cadillac] => 4
[Ford] => 5
[countTotal] => 6
)
I am trying to figure out a way to create a new array with the right values from array 1 but that is in the order of array 2.
I have been playing with it for awhile and cannot seem to get it.
Any help would be great.
Thanks!
$c = array();
foreach (array_keys($b) as $k) {
$c[k] = $a[k];
}
You could use php's array_multisort function:
$original = array(
'countTotal' => 7268,
'zip' => '',
'yearName' => '',
'countZipRadius' => '',
'Acura' => 1334,
'Cadillac' => 511,
'Ford' => 5423,
);
$right = array(
'countZipRadius' => 0,
'zip' => 1,
'yearName' => 2,
'Acura' => 3,
'Cadilac' => 4,
'Ford' => 5,
'countTotal' => 6
);
//make sure both arrays are in the same order
ksort($original);
ksort($right);
array_multisort($right, $original);
print_r($original);
When you give it two arrays with the same number of elements it sorts both arrays, based on the order of the first array - in this case the 0, 1, 2, 3, etc. values in $right
Create a New Array (Array C)
Use a FOR loop to go through Array B
For each value in Array B, get the value with the same key from Array A and set Array C append those values to Array C. This will put them in the correct order in C.
Using scones' method:
$original = array(
'countTotal' => 7268,
'zip' => '',
'yearName' => '',
'countZipRadius' => '',
'Acura' => 1334,
'Cadillac' => 511,
'Ford' => 5423,
);
$right = array(
'countZipRadius' => 0,
'zip' => 1,
'yearName' => 2,
'Acura' => 3,
'Cadilac' => 4,
'Ford' => 5,
'countTotal' => 6
);
foreach ($right as $key => $value) {
$new[$key] = $original[$key];
}
print_r($new);
$array = array('a' => 100, 'b' => '5');
$newArray = array_combine(array_keys($array), range(0, count($array) - 1));
var_dump($newArray);