Issue with array_map callback - php

At first I had this (work in wamp but not in my web server)
$ids = array_map(function($item) { return $item['user_id']; }, $data['student_teacher']);`
So I try to convert the code to that but nothing work ( i got Array,Array,Array,Array,Array,Array from outpout )
$ids = array_map($this->myarraymap(null), $data['student_teacher']);
function myarraymap($item) {
return $item['user_id'];
}

You need to pass it a callback, and not actually pass it the execution of the function, i.e.,
$ids = array_map(array($this, 'myarraymap'), $data['student_teacher']);
function myarraymap($item) {
return $item['user_id'];
}

Related

PHP Using code as a function, variables not working

I've got this code which works well standalone:
file_put_contents('dataFile', implode('',
array_map(function($data) {
return stristr($data,"NSQ = ") ? "NSQ = school\n" : $data;
}, file('dateFile'))
));
This reads dataFile and finds the entry NSQ = and updates it to be NSQ = school
I'm going to reuse this multple times so changed it into a function:
function updatesite($site) {
file_put_contents('dataFile', implode('',
array_map(function($data) {
return stristr($data,"$site = ") ? "$site = school\n" : $data;
}, file('dateFile'))
));
}
Initially, I got an error that $site didn't exist, so I added global $site; before the return.
That stopped the error, but it doesn't update the file.
Is there any way I can use a variable like this?
You can use use to pass variables to a function callback like this:
function updatesite($site) {
file_put_contents('dataFile', implode('',
array_map(function($data) use ($site) {
return stristr($data,"$site = ") ? "$site = school\n" : $data;
}, file('dateFile'))
));
}

Laravel : I want to return the result of chunk function , to get it in the view with Ajax

I want to return the result of chunk. The problem is , when I iterate with foreach, I put echo result it displays the result but when I want to return it , I have a blank page
$tab = array();
Product::blabla ->chunk (500, function($results))
{
foreach($results as $result)
{
array_push ($tab,$result);
echo $results;// works
return $results;// doesn't return anything
}
}
return $tab; // to be sent to Ajax type get
Closure can be stored into variable, so just add to variable.
$tab = Product::blabla()->chunk (500, function($results))
{
// your logic
return $results;
};
return $tab
This is not working actually, it just return true. You have to make the closure function use an external variable by reference example:
$output = [];
$tab = Product::blabla()->chunk (500, function($results) use (&$output))
{
$output = array_combine($output, $results);
};
return $output;

Find an Object in an array by comparing Object->value to all Object->values in array PHP

So my array contains objects like this:
$arr = array(
new Card('10', 'Spades'),
new Card('Jack', 'Diamonds'),
new Card('King', 'Spades')
);
Now I have a function:
function hasCard(Card $card) {
if (in_array($card, $arr)) return true;
return false;
}
Now above does not really work since I need to compare ($card->rank == $arr[$x]->rank) for each element in that $arr without looping. Is there a function on PHP that allows you to modify the compareTo method of array_search?
I'd suggest using array_filter here. (Note: make sure $arr is available inside the hasCard function)
function hasCard(Card $card) {
$inArray = array_filter($arr, function($x) use($card){
return $x->rank === $card->rank;
});
return count($inArray) > 0;
}
DEMO: https://eval.in/166460
The $arr variable is not going to be available within the function hasCard, unless you pass it as a parameter.
To answer your question, look at array_filter. This will get you a callable function in which you can pass the $arr and $card as parameters.

Recursive function with unknown depth of values. Return all values (undefined depth)

I have a question about a recursive PHP function.
I have an array of ID’s and a function, returning an array of „child id’s“ for the given id.
public function getChildId($id) {
…
//do some stuff in db
…
return childids;
}
One childid can have childids, too!
Now, I want to have an recursive function, collecting all the childids.
I have an array with ids like this:
$myIds = array("1111“,"2222“,"3333“,“4444“,…);
and a funktion:
function getAll($myIds) {
}
What I want: I want an array, containing all the id’s (including an unknown level of childids) on the same level of my array. As long as the getChildId($id)-function is returning ID’s…
I started with my function like this:
function getAll($myIds) {
$allIds = $myIds;
foreach($myIds as $mId) {
$childids = getChildId($mId);
foreach($childids as $sId) {
array_push($allIds, $sId);
//here is my problem.
//what do I have to do, to make this function rekursive to
//search for all the childids?
}
}
return $allIds;
}
I tried a lot of things, but nothing worked. Can you help me?
Assuming a flat array as in your example, you simply need to call a function that checks each array element to determine if its an array. If it is, the function calls it itself, if not the array element is appended to a result array. Here's an example:
$foo = array(1,2,3,
array(4,5,
array(6,7,
array(8,9,10)
)
),
11,12
);
$bar = array();
recurse($foo,$bar);
function recurse($a,&$bar){
foreach($a as $e){
if(is_array($e)){
recurse($e,$bar);
}else{
$bar[] = $e;
}
}
}
var_dump($bar);
DEMO
I think this code should do the trick
function getAll($myIds) {
$allIds = Array();
foreach($myIds as $mId) {
array_push($allIds, $mId);
$subids = getSubId($mId);
foreach($subids as $sId) {
$nestedIds = getAll($sId);
$allIds = array_merge($allIds, $nestedIds);
}
}
return $allIds;
}

How to Promote certain elements to the start of an array in PHP

If certain elements are contained in an array, I want them moved to the start of it.
At first I used a bunch of array_diff_keys to get it to work, but I wanted something more elegant. So I tried using uksort with a callback, but perhaps I'm doing it wrong because it's not working.
I tried this, it's a method of my helper class, but it's not working.
$good_elements = array('sku','name','type','category','larping');
$test_array = array('sku','name','asdf','bad_stuff','larping','kwoto');
$results = helper::arrayPromoteElementsIfExist($test_array,$good_elements,false);
public static function arrayPromoteElementsIfExist($test_array,$promote_elements,$use_keys = false) {
foreach(array('test_array','promote_elements') as $arg) {
if(!is_array($$arg)) {
debug::add('errors',__FILE__,__LINE__,__METHOD__,'Must be array names',$$arg);
return false;
}
}
if(!$use_keys) {
$test_array = array_flip($test_array); // compare keys
$promote_elements = array_flip($promote_elements); // compare keys
}
uksort($test_array,function($a,$b) use($promote_elements) {
$value1 = intval(in_array($a, $promote_elements));
$value2 = intval(in_array($b,$promote_elements));
return $value1 - $value2;
});
if(!$use_keys) {
$test_array = array_flip($test_array);
}
return $test_array;
}
Fairly quick and dirty but here you go.
function promoteMembers($input, $membersToPromote)
{
$diff = array_diff($input, $membersToPromote);
return array_merge($membersToPromote, $diff);
}
Assuming I understood what you wanted to do.
Example output: for your verification.

Categories