get set elements from array php - php

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;
}
}

Related

Find similar items in PHP object

I've been trying and trying on this and can't seem to work it out on my own.
So could someone please show me the direction I want to take with this?
I want to be able to implode the object items which contain the string - grade_id.
I've tried getting them all by using array_filter() etc. However seems to not return back the right values.
array_keys() doesn't bring anything back either to try and match array_keys with a preg_match.
I'm just looking for some guidance for this, you don't have to give me a full answered answer, just a point in the right direction.
meeting Object
(
[errors] => 0
[id] => 1
[school_id] => 1
[staff_id] => 2
[grade_id] => 85
[grade_id_2] => 0
[grade_id_3] => 0
[grade_id_4] => 0
[grade_id_5] => 0
[grade_id_6] => 0
[grade_id_7] => 0
[grade_id_8] => 0
[grade_id_9] => 0
[grade_id_10] => 0
[inserted] => 2018-02-19 11:46:13
[updated] => 2018-02-19 12:00:31
)
Result i'm looking for is: (I'm wanting to find a way without using a loop "If possible")
$grade_ids = "85";
You can do this if you convert your object into array:
$array = (array)$object;
/* find keys in array that contain 'grade_id' */
$keys = preg_grep('/grade_id/', array_keys($array));
/* discard other array elements */
$filtered = array_intersect_key($array, array_flip($keys));
$result = implode(',', $filtered);
You can use array_walk_recursive(), I try like this code:
$var = array('meeting'=> array("errors" => 0,
"id" => 1,
"school_id" => 1,
"staff_id" => 2,
"grade_id" => 85,
"grade_id_2" => 0,
"grade_id_3" => 0,
"grade_id_4" => 0,
"grade_id_5" => 0,
"grade_id_6" => 0,
"grade_id_7" => 0,
"grade_id_8" => 0,
"grade_id_9" => 0,
"grade_id_10" => 0,
"inserted" => "2018-02-19 11:46:13",
"updated" => "2018-02-19 12:00:31"));
$uniques = array();
array_walk_recursive($var, function($val, $key) use (&$uniques){
$i=2;
if($key == 'grade_id') {
$uniques[] = $val;
} if($key == 'grade_id_'.$i) {
$uniques[] = $val;
}
$i++;
});
$uniques = array_unique($uniques);
print_r($uniques);
and output is:
Array ( [0] => 85 [1] => 0 )

fill in the multidimensional array with missing keys

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);
}

Merge 2 element of same array into one in php

I have an array
Array
(
[0] => Array
(
[hrg_lid] => 214291464161204318
[pecon] => 0
[col2pe] => Karam
[col4pe] => 1
[col6pe] => 2
[col8pe] => 264
[col9pe] => 42
[col10pe] => 85
[col11pe] => 2
)
[1] => Array
(
[hrg_lid] => 707581464079555092
[pecon] => 1
[col2pe] => Dummy
[col4pe] =>
[col6pe] =>
[col8pe] => 12
[col9pe] => 0
[col10pe] => 0
[col11pe] => 2
[col12pe] => 1
[col13pe] => 1
)
[2] => Array
(
[hrg_lid] => 707581464079555092
[col5risk] => 2
[col6risk] => 2
[col7risk] => 1
[col8risk] => 2
[col9risk] => 1
[col10risk] => 1
[col11risk] => 2
)
I want to merge those elements which has same hrg_lid.
Expected Output
Array
(
[0] => Array
(
[hrg_lid] => 214291464161204318
[pecon] => 0
[col2pe] => Karam
[col4pe] => 1
[col6pe] => 2
[col8pe] => 264
[col9pe] => 42
[col10pe] => 85
[col11pe] => 2
)
[1] => Array
(
[hrg_lid] => 707581464079555092
[pecon] => 1
[col2pe] => Dummy
[col4pe] =>
[col6pe] =>
[col8pe] => 12
[col9pe] => 0
[col10pe] => 0
[col11pe] => 2
[col12pe] => 1
[col13pe] => 1
[col5risk] => 2
[col6risk] => 2
[col7risk] => 1
[col8risk] => 2
[col9risk] => 1
[col10risk] => 1
[col11risk] => 2
)
I tried following code
foreach($arr as $key => $value) {
$finalArray[$value['hrg_lid']] = $value;
}
but fails
I would use hrg_lid as array key - otherwise you have to check every element already in the output array for matches every time you add a new element:
$finalArray = array();
foreach($arr as $value) {
$hrg_lid = $value['hrg_lid'];
if (isset($finalArray[$hrg_lid])) {
// merge if element with this $hrg_lid is already present
$finalArray[$hrg_lid] = array_merge($finalArray[$hrg_lid], $value);
} else {
// save as new
$finalArray[$hrg_lid] = $value;
}
}
If you want to get normalized array keys, you can reset them afterwards:
$finalArray = array_values($finalArray);
The hrg_lid value must be the key of the array, if you won't change the keys, Try this :
for($i=0; $i < count($arr);$i++)
{
for($j=0; $j < count($finalArray);$j++)
{
if($arr[$i]['hrg_lid'] == $finalArray[$j]['hrg_lid'])
{
$finalArray[$j] = array_merge($finalArray[$j],$arr[$i]);
break;
}
}
}
Try soomething like :
$finalArray = [];
foreach($arr as $singleArray) {
$id = $singleArray['hrg_lid'];
if (isset($finalArray[$id])) {
$finalArray = array_merge($finalArray[$id], $singleArray);
} else {
$finalArray[] = $singleArray;
}
}
You could try something like that :
$tmpArray = array();
$finalArray = array();
// We merge the arrays which have the same value in 'hrg_lid' col
foreach($source as $array){
$key = $array['hrg_lid'];
array_shift($array);
if(array_key_exists($key, $tmpArray)){
$tmpArray[$key] = array_merge($tmpArray[$key], $array);
}else{
$tmpArray[$key] = $array;
}
}
// We build the final array
foreach($tmpArray as $key => $value){
$finalArray[] = array_merge(array('hrg_lid' => $key), $value);
}

how to convert multi array to json multi array

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.

Add item to array of arrays based on id

I have an array of arrays set up like so. There are a total of 10 arrays but I will just display the first 2. The second column has a unique id of between 1-10 (each only used once).
Array
(
[0] => Array
(
[0] => User1
[1] => 5
)
[1] => Array
(
[0] => User2
[1] => 3
)
)
I have another array of arrays:
Array
(
[0] => Array
(
[0] => 3
[1] => 10.00
)
[1] => Array
(
[0] => 5
[1] => 47.00
)
)
where the first column is the id and the second column is the value I want to add to the first array.
Each id (1-10) is only used once. How would I go about adding the second column from Array#2 to Array#1 matching the ID#?
There are tons of ways to do this :) This is one of them, optimizing the second array for search and walking the first one:
Live example
<?
$first_array[0][] = 'User1';
$first_array[0][] = 5;
$first_array[1][] = 'User2';
$first_array[1][] = 3;
$secnd_array[0][] = 3;
$secnd_array[0][] = 10.00;
$secnd_array[1][] = 5;
$secnd_array[1][] = 47.00;
// Make the user_id the key of the array
foreach ($secnd_array as $sca) {
$searchable_second_array[ $sca[0] ] = $sca[1];
}
// Modify the original array
array_walk($first_array, function(&$a) use ($searchable_second_array) {
// Here we find the second element of the first array in the modified second array :p
$a[] = $searchable_second_array[ $a[1] ];
});
// print_r($first_array);
Assuming that 0 will always be the key of the array and 1 will always be the value you'd like to add, a simple foreach loop is all you need.
Where $initial is the first array you provided and $add is the second:
<?php
$initial = array(array("User1", 5),
array("User2", 3));
$add = array(
array(0, 10.00),
array(1, 47.00));
foreach ($add as $item) {
if (isset($initial[$item[0]])) {
$initial[$item[0]][] = $item[1];
}
}
printf("<pre>%s</pre>", print_r($arr1[$item[0]], true));
I don't know if I got you right, but I've come up with a solution XD
<?php
$array_1 = array(
0 => array(
0 => 'ID1',
1 => 5
),
1 => array(
0 => 'ID2',
1 => 3
)
);
$array_2 = array(
0 => array(
0 => 3,
1 => 10.00
),
1 => array(
0 => 5,
1 => 47.00
)
);
foreach($array_1 as $key_1 => $arr_1){
foreach($array_2 as $key_2 => $arr_2){
if($arr_2[0] == $arr_1[1]){
$array_1[$key_1][2] = $arr_2[1];
}
}
}
var_dump($array_1);
?>
Demo: https://eval.in/201648
The short version would look like this:
<?php
$array_1 = array(array('ID1',5),array('ID2',3));
$array_2 = array(array(3,10.00),array(5,47.00));
foreach($array_1 as $key => $arr_1){
foreach($array_2 as$arr_2){
if($arr_2[0] == $arr_1[1]){
$array_1[$key][2] = $arr_2[1];
}
}
}
var_dump($array_1);
?>
Demo: https://eval.in/201649
Hope that helps :)
A quick and dirty way just to show you one of the more self-explaining ways to do it :)
$users = array(
0 => array(
0 => 'User1',
1 => 123
),
1 => array(
0 => 'User2',
1 => 456
)
);
$items = array(
0 => array(
0 => 123,
1 => 'Stuff 1'
),
1 => array(
0 => 456,
1 => 'Stuff 2'
)
);
foreach($items as $item){
foreach($users as $key => $user){
if($item[0] == $user[1])
array_push($users[$key], $item[1]);
}
}

Categories