make a particular element to be first in array - php

I've an array like this
$arrList = Array (
[0] => Array
(
[master] => Array
(
[id] => 3
[name] => Test
)
)
[1] => Array
(
[master] => Array
(
[id] => 4
[name] => Sample
)
)
)
Now, I know the value of the id,how can I re-arrange with the particular value of id to be on the top..(i.e.,whatever the value of id that I have in a variable that should be on top of the array, if I get the value of id as 4 then the array should be
$arrList = Array (
[0] => Array
(
[master] => Array
(
[id] => 4
[name] => Sample
)
)
[1] => Array
(
[master] => Array
(
[id] => 3
[name] => Test
)
)
)
thanks in advance..

Just try this code
foreach($arrList as $Key => $array) {
if($id == $array['master']['id']){ //check the value with all [master][id]
$arr[] = $array; // setting up the respective array to another array
$iKey = $Key; // getting the key value of that particular array
}
}
if(isset($iKey) && $iKey != NULL){
unset($arrList[$iKey]); // removing the key value from the main array
array_splice($arrList, 0, 0, $arr);
//using this function setting up again the array to the 0th index,
}
for any other index value, mention as second parameter in above function, suppose if you need to have as third index then it should be..
array_splice($arrList, 3, 0, $arr);

function cmp($a, $b)
{
if ($a['master']['id'] == $b['master']['id']) {
return 0;
}
return ($a['master']['id'] > $b['master']['id']) ? -1 : 1;
}
$a = Array (
0 => Array (
'master' => Array
(
'id' => 3,
'name' => 'Test',
)
),
'1' => Array
(
'master' => Array
(
'id' => 4,
'name' => 'Sample',
)
)
);
usort($a, "cmp");
print_r($a);

You can sort the array with a special sort function. The code is:
usort($array, function($a,$b){ return $b['master']['id']==4; });

Try this, I have created example here
http://codepad.org/z4oI9KHk

Related

How to remove array from array if value have related to other value in array in PHP?

I have an array and want to remove the related value form array.
Ex.
In array [0] have 1/2/3 and [1] have 1/2/3/4 then [0] is a related to [1] so
remove [0] which have 1/2/3 from the array.
Another Example is
Ex.
[2] have 1/2/5, [3] have 1/2/5/6 and [4] have 1/2/5/6/7 then [2] and
[3] depends on [4] so remove [2] and [3] both array form array.
For more details please check below example.
Array
(
[0] => Array
(
[id] => 1/2/3
)
[1] => Array
(
[id] => 1/2/3/4
)
[2] => Array
(
[id] => 1/2/5
)
[3] => Array
(
[id] => 1/2/5/6
)
[4] => Array
(
[id] => 1/2/5/6/7
)
)
Want Output :
Array
(
[0] => Array
(
[id] => 1/2/3/4
)
[1] => Array
(
[id] => 1/2/5/6/7
)
)
I don't have an idea how can I do that. Is it possible?
Assuming that the array is in order, you can array_reverse the array. Use array_reduce to loop thru the array, Use strpos to check position of the first occurrence of a substring in a string.
$arr = //your array
$result = array_reduce( array_reverse( $arr ), function( $c, $v ){
if ( count( $c ) === 0 ) $c[] = $v;
else if ( count( $c ) && strpos( $c[0]['id'] , $v['id'] ) === false ) array_unshift( $c, $v );
return $c;
}, array());
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[id] => 1/2/3/4
)
[1] => Array
(
[id] => 1/2/5/6/7
)
)
Of course it is possible. You need to sort the elements first and then it is very straightforward.
<?php
$input = [
[ "id" => "1/2/3" ],
[ "id" => "1/2/3/4" ],
[ "id" => "1/2/5" ],
[ "id" => "1/2/5/6" ],
[ "id" => "1/2/5/6/7" ]
];
//firstly sort this array in reverse order
//like so 1/2/3/4 is before 1/2/3
usort(
$input,
function($e1, $e2) {
return $e2["id"] <=> $e1["id"];
}
);
$output = array_reduce(
$input,
function($out, $el) {
if (empty($out)) {
$out[] = $el;
} else {
$lastEl = $out[count($out) - 1];
//we add element to the result array
//only if actual last element doesn't begin with it
if (strpos($lastEl['id'], $el['id']) !== 0) {
$out[] = $el;
}
}
return $out;
},
[]
);
var_dump($output);

Removing subarrays that share a key-value pair with another multidimensional array

I have 2 arrays as below. I want to remove data from array2 if array1 has the stu_id. final array should be like result_array.
$array1 = Array
(
[0] => Array
(
[stu_id] => 1
[name] => mr.a
)
[1] => Array
(
[stu_id] => 3
[name] => mr.b
)
)
$array2 = Array
(
[0] => Array
(
[id] => 1
[stu_id] => 1
[data] => abc
)
[1] => Array
(
[id] => 2
[stu_id] => 2
[data] => xyz
)
[3] => Array
(
[id] => 3
[stu_id] => 3
[data] => aaa
)
)
$result_array = Array
(
[0] => Array
(
[id] => 2
[stu_id] => 2
[data] => xyz
)
)
I tried array_diff, $result_array = array_diff($array2, $array1); but it's not working.
Please help me to do this.
Temporarily assign keys using array_column() with stud_id (NULL retains the full subarray data), then use array_diff_key() to filter, and array_values() to reset the keys:
Code: (Demo)
$array1=[
['stu_id'=>1,'name'=>'mr.a'],
['stu_id'=>3,'name'=>'mr.b']
];
$array2=[
['id'=>1,'stu_id'=>1,'data'=>'abc'],
['id'=>2,'stu_id'=>2,'data'=>'xyz'],
['id'=>3,'stu_id'=>3,'data'=>'aaa']
];
//var_export(array_column($array1,NULL,'stu_id'));
//var_export(array_column($array2,NULL,'stu_id'));
var_export(array_values(array_diff_key(array_column($array2,NULL,'stu_id'),array_column($array1,NULL,'stu_id'))));
Output:
array (
0 =>
array (
'id' => 2,
'stu_id' => 2,
'data' => 'xyz',
),
)
If you'd like to use a foreach loop structure, generate a filtering array of stu_id's from $array1 and write a conditional check on each iteration of $array2. This method doesn't not modify the original arrays, so they can be reused "down script".
Code:
$stu_ids=array_column($array1,'stu_id');
foreach($array2 as $row){
if(!in_array($row['stu_id'],$stu_ids)){
$result[]=$row; // auto-index the qualifying subarrays
}
}
var_export($result);
// same result as above method
foreach($array1 as $data1){
foreach($array2 as $k => $data2){
if($data2["stu_id"] == $data1["stu_id"]){
unset($array2[$k]);
break;
}
}
}
$result_array = $array2;

How to combine inner array values in one multidimensional array?

Hi I have one multidimensional array, I retrieved the data using mysql PDO and formatted it this way
array('id'=>$row['empname'],'data'=>array(array($row['salestat'],$row['salecount'])))
Array
(
[0] => Array
(
[id] => 'employee1'
[data] => Array
(
0 => 'Sold'
1 => 1
)
)
[1] => Array
(
[id] => 'employee2'
[data] => Array
(
0 => 'On Process'
1 => 4
)
)
[2] => Array
(
[id] => 'employee2'
[data] => Array
(
0 => 'Sold'
1 => 2
)
)
)
I am trying to make my output like this, trying to format this so I can use it for drilldown series in highcharts, thank you
Array
(
[0] => Array
(
[id] => 'employee1'
[data] => Array
(
0 => 'Sold'
1 => 1
)
)
[1] => Array
(
[id] => 'employee2'
[data] => Array
[0]
(
0 => 'On Process'
1 => 4
)
[1]
(
0 => 'Sold'
1 => 2
)
)
)
Firstly, you can not use a field inside an array twice with the same key like salescount or salestat. But you can do something like this.
function wrapSameId( $employeeArray ) {
//create the new array.
$newEmployeeArray = array();
//loop the old array.
foreach ($employeeArray as $key => $value) {
$exists = 0;
$i=0;
$id = $value['id'];
$data = $value['data'];
//see if you can find the current id inside the newly created array if you do, only push the new data in.
foreach ($newEmployeeArray as $key2 => $value2) {
if( $id == $value2['id'] ) { $newEmployeeArray[$key2]['data'][] = $data;$exists = 1;var_dump($value2['data']); }
$i++;
}
//if we didnt find the id inside the newly created array, we push the id and the new data inside it now.
if( $exists == 0 ){
$newEmployeeArray[$i]['id'] = $id;
$newEmployeeArray[$i]['data'][] = $data;
}
}
return $newEmployeeArray;
}
This function should return a new Array but if in the old array there were multiple arrays with the same id, in this one we should have:
Array
(
[0] => Array
(
[id] => employee1
[data] => Array
(
[0] => Array
(
[salescount] => 4
[salesstat] => Sold
)
)
)
[1] => Array
(
[id] => employee2
[data] => Array
(
[0] => Array
(
[salescount] => 2
[salesstat] => In Progress
)
[1] => Array
(
[salescount] => 5
[salesstat] => Sold
)
)
)
)
You can use it like this:
$employees = wrapSameId( $PDOArray );
where $PDOArray is your initial Array. Hope this is what you were looking for.
Why not index your output array by id?
Loop over your initial array and add the salecount, salestat pair to an employee's data array.
$outputArray = array();
//Loop over each entry pulled from you database...
foreach ($employeeArray as $employeeInfo)
{
//If no index for the current employee exists, create an empty array
//The only reason I'm including this is because I'm not sure how array_merge handles nulls -- just to be safe
if (!$outputArray[$employeeInfo['id']])
{
$outputArray[$employeeInfo['id']] = array();
}
//Merge the existing array for that employee with the new data for the same employee
$outputArray[$employeeInfo['id']] = array_merge($outputArray[$employeeInfo['id']], $employeeInfo['data']);
}
print_r($outputArray);
It's easier to visualize the output...
Array
(
[employee1] => Array
(
0 => 1
1 => 'Sold'
)
[employee2] => Array
(
0 => 4
1 => 'On Process'
2 => 2
3 => 'Sold'
)
)
If you're not satisfied with your output being indexed by id, loop over it again and format it as you want.
$otherOutputArray = array();
foreach ($outputArray as $key => $value)
{
$otherOutputArray[] = array('id' => $key, 'data' => $value);
}
That gives you exactly what you want.

How to intersect Array of objects in PHP?

How do i get the result of intersection between two Array of Objects in PHP.
For Example,
the value of $array1 is
Array
(
[0] => stdClass Object
(
[id] => 2
[influencer_id] => 2
[follower_id] => 1
)
)
and the value of $array2 is,
Array
(
[0] => stdClass Object
(
[id] => 2
[influencer_id] => 1
[follower_id] => 2
),
[1] => stdClass Object
(
[id] => 3
[influencer_id] => 3
[follower_id] => 2
),
)
So, what i want to get in $result is
Array
(
[0] => stdClass Object
(
[id] => 2
[influencer_id] => 2
[follower_id] => 1
)
)
What is the best way to get it?
Thanks in advance!
You can do that using array_uintersect function and defining manually your callback comparison function :
$arr1 = json_decode('[{"id":2,"influencer_id":2,"follower_id":1}]');
$arr2 = json_decode('[{"id":2,"influencer_id":2,"follower_id":1},{"id":3,"influencer_id":3,"follower_id":2}]');
$arr3 = array_uintersect($arr1, $arr2, function ($e1, $e2) {
if($e1->id == $e2->id && $e1->influencer_id == $e2->influencer_id && $e1->follower_id == $e2->follower_id) {
return 0;
} else {
return 1;
}
});
var_dump($arr3);
Try to use array_intersect
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

How to Get Specific key array in php without any loop

I have one multi dimentional array, the problem is I want the array values of specific key. I already tried current() and end() of array which is not useful to me. So please suggest me appropriate solution to find array values of specific key without using any loop. My Demo array is
Array
(
[0] => Array
(
[EntityType] => Array
(
[Id] => 1
[Code] => SUP/13-14/10001
[Name] => Supplier
[DisplayName] => Supplier
[ModuleIdentifier] => 1
[IsAdd] =>
[IsEdit] => 1
[IsDelete] => 1
)
)
[1] => Array
(
[EntityType] => Array
(
[Id] => 2
[Code] => Emp/13-14-10002
[Name] => Employee
[DisplayName] => Employee
[ModuleIdentifier] => 1
[IsAdd] =>
[IsEdit] =>
[IsDelete] =>
)
)
[2] => Array
(
[EntityType] => Array
(
[Id] => 3
[Code] => CUS/13-14/10003
[Name] => Customer
[DisplayName] => Customer
[ModuleIdentifier] => 1
[IsAdd] => 1
[IsEdit] =>
[IsDelete] =>
)
)
)
I want array having name Customer. So how to get these array...
Thanks !
You may use array_filter in conjunction with array_map:
function findElem($array, $val) {
$result = array_map(
function ($v) { return $v['EntityType']; },
array_filter($array, function ($v) use($val) { return $v['EntityType']['Name'] == $val; })
);
return count($result)? $result[0] : false;
}
print_r(findElem($array, 'Customer'));
If you want to access n'th element of your array just try with:
$array[n]
Where n is an integer value, so:
$array[2]
This line will get you all values of the key "Name" assuming your source array is named $arr if that's what you wanted:
$names = array_map( function($item) { return $item["EntityType"]["Name"]; } , $arr );
You can access your array data like this: $array[0]["EntityType"]["ID"].

Categories