How can i add element to my array under a specific key? - php

How can i add element to my array under a specific key?
This is my array output before i use foreach. As you can see, the error field is empty. I want to fill it out.
Array (
[0] => Array (
[transactionid] => 2223
[created] => 26-02-13 14:07:00
[cardid] => 10102609
[pricebefordiscount] => 68900
[error] =>
)
This is my foreach. As you can see i already tried to make this work by implementing $arrayname['index'] = $value;. But this does not work, nothing comes out when i spit out in a print_r. Why is this happening?
foreach ($samlet as $key)
{
if ($key['pricebefordiscount'] > '200000')
{
$samlet['error'] = "O/2000";
}
if ($key['cardid'] === '88888888')
{
$samlet['error'] = "Testscan";
}
}
This is the desired output:
Array (
[0] => Array (
[transactionid] => 2223
[created] => 26-02-13 14:07:00
[cardid] => 10102609
[pricebefordiscount] => 68900
[error] => "Testscan"
)

Change your foreach, so you have the indexes used in the "main" $samlet array:
foreach($samlet as $key => $array)
{
if ($array['cardid'] === '88888888')
{
$samlet[$key]['error'] = '0/2000';
}
}
And so on...

Try this :
foreach ($samlet as &$key){
if ($key['pricebefordiscount'] > '200000'){
$key['error'] = "O/2000";
}
if ($key['cardid'] === '88888888'){
$key['error'] = "Testscan";
}
}

According to PHP manual:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
So your code should looke like this:
<?php
foreach ($samlet as &$key)
{
if ($key['pricebefordiscount'] > '200000')
{
$key['error'] = "O/2000";
}
if ($key['cardid'] === '88888888')
{
$key['error'] = "Testscan";
}
}

TRY THIS
foreach ($samlet as $key=>$value)
{
if ($value['pricebefordiscount'] > '200000')
{
$samlet[$key]['error'] = "O/2000";
}
if ($value['cardid'] === '88888888')
{
$samlet[$key]['error'] = "Testscan";
}
}

Related

Search nested multidimensional array

I have a function that fills an array:
foreach ($request->get('ids') as $id) {
$pdfArray['other']++; // Yes this is initialized
$pdfArray['rows'][$i]['id'] = $schedule->getId();
$pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
$pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
$pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
$pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
$pdfArray['rows'][$i]['desc'] = $schedule->getDescription();
}
What I want to do
On each loop, I want to check if the array (so far) already has a desc entry equal to the current $schedule->getDescription() AND the same date as $schedule->getStart()->format('d.m.Y') (actually more, but let's keep it simple)
What I tried
public function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && $this->recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Source
I use it like that:
if ($this->recursive_array_search($schedule->getDescription(), $pdfArray['rows']) &&
$this->recursive_array_search($schedule->getStart()->format('d.m.Y'), $pdfArray['rows'])){
$pdfArray['ma'][$schedule->getId()]++;
}
but this is true when ANY of the start or desc are SOMEWHERE in the current array.
How would I check if desc is found and start is in the SAME $i level?
EDIT for example
Let's say I have 10 $ids to loop through. After 2 loops, the $pdfArray looks like this:
Array
(
[other] => 2
[rows] => Array
(
[0] => Array
(
[id] => 1
[date] => 13.07.2016
[dateSort] => 2016-07-13 08:00
[from] => 08:00
[to] => 09:00
[desc] => TEST
)
[1] => Array
(
[id] => 2
[date] => 12.07.2016
[dateSort] => 2016-07-12 08:00
[from] => 08:00
[to] => 09:00
[desc] => TEST
)
)
)
The next iteration has the following:
$schedule->getStart()->format('d.m.Y') => 12.07.2016
$schedule->getDescription() => TEST
So I want to have the info that the combination already exists in the array.
BUT
$schedule->getStart()->format('d.m.Y') => 12.07.2016
$schedule->getDescription() => TEST2
should NOT return true upon checking of it exists.
To test for a "duplicate" you can use this function:
function testPresence($pdfArray, $desc, $date) {
foreach ($pdfArray["rows"] as $row) {
if ($row["desc"] == $desc && $row["date"] == $date) return true;
}
}
Example use:
echo testPresence($pdfArray, "TEST2", "12.07.2016") ? "Found" : "Not found"; // Not found
echo testPresence($pdfArray, "TEST", "12.07.2016") ? "Found" : "Not found"; // Found
In your original loop, you can use it as follows:
foreach ($request->get('ids') as $id) {
if (testPresence($pdfArray, $schedule->getDescription(),
$schedule->getStart()->format('d.m.Y')) {
// We have a duplicate. Maybe skip this entry?:
continue;
}
$pdfArray['other']++;
$pdfArray['rows'][$i]['id'] = $schedule->getId();
$pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
$pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
$pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
$pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
$pdfArray['rows'][$i]['desc'] = $schedule->getDescription();
}
try this at your validation function
public function array_search($needle1, $needle2 ,$haystack) {
foreach($haystack as $singleArray){
if (in_array($needle1, $singleArray) && in_array($needle2, $singleArray))
return true;
else
continue;
}
return false;
}
and invoke your recursive_array_search like this
if ($this->array_search($schedule->getStart(), $schedule->getDescription(), $pdfArray['rows'])
continue;//Or any other kind of logic you want. At this place you know that description and date staet exist in at your array level
$pdfArray['other']++; // Yes this is initialized
$pdfArray['rows'][$i]['id'] = $schedule->getId();
$pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
$pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
$pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
$pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
$pdfArray['rows'][$i]['desc'] = $schedule->getDescription();
Function version:
/**
* Find matches for $item into pdfArray.
* Returns an index array, possibly empty if no matches.
* #param $item item to find
* #param $rows rows where to search
*/
function findPdfArrayMatches(array $item, array $rows) {
return array_keys(
array_filter(
$rows,
function ($entry) use ($item) {
// These are the matching criteria. More than one row may match.
return $entry['desc'] == $item['desc']
&& $entry['date'] == $item['date']
;
}
)
);
}
You could do like this, in the loop:
$item = [
'id' => $schedule->getId(),
'date' => $schedule->getStart()->format('d.m.Y'),
'dateSort' => $schedule->getStart()->format('Y-m-d H:i'),
'from' => $schedule->getStart()->format('H:i'),
'to' => $schedule->getEnd()->format('H:i'),
'desc' => $schedule->getDescription(),
];
$matches = findPdfArrayMatches($item, $pdfArray['rows']);
if (!empty($matches)) {
...do something with the matches:
foreach ($matches as $match) {
$pdfArray['rows'][$match]['Duplicate'] = true;
}
}
// Add new item
$pdfArray['rows'][$i] = $item;

How to find object in php array and delete it?

Here is print_r output of my array:
Array
(
[0] => stdClass Object
(
[itemId] => 560639000019
[name] => Item no1
[code] => 00001
[qty] => 5
[id] => 2
)
[1] => stdClass Object
(
[itemId] => 470639763471
[name] => Second item
[code] => 76347
[qty] => 9
[id] => 4
)
[2] => stdClass Object
(
[itemId] => 56939399632
[name] => Item no 3
[code] => 39963
[qty] => 6
[id] => 7
)
)
How can I find index of object with [id] => 4 in order to remove it from array?
$found = false;
foreach($values as $key => $value) {
if ($value->id == 4) {
$found = true;
break;
}
}
if ($found) unset($values[$key]);
This is considered to be faster then any other solution since we only iterate the array to until we find the object we want to remove.
Note: You should not remove an element of an array while iterating so we do it afterwards here.
foreach($parentObj AS $key=>$element){
if ($element->id == THE_ID_YOU_ARE_LOOKING_FOR){
echo "Gottcha! The index is - ". $key;
}
}
$parentObj is obviously your root array - the one that holds all the others.
We use the foreach loop to iterate over each item and then test it's id property against what ever value you desire. Once we have that - the $key that we are on is the index you are looking for.
use array_search:
$a = new stdClass;
$b = new stdClass;
$a->id = 1;
$b->id = 2;
$arr = array($a, $b);
$index = array_search($b, $arr);
echo $index;
// prints out 1
try this
foreach($array AS $key=>$object){
if($object['id'] == 4){
$key_in_array = $key;
}
}
// chop it from the original array
array_slice($array, $key_in_array, 1);
Another way to achieve the result is to use array_filter.
$array = array(
(object)array('id' => 5),
(object)array('id' => 4),
(object)array('id' => 3)
);
$array = array_filter($array, function($item) {
return $item->id != 4;
});
print_r($array);
Here's my solution. Given, it is a bit hackish, but it will get the job done.
search(array $items, mixed $id[, &$key]);
Returns the item that was found by $id. If you add the variable $key it will give you the key of the item found.
function search($items, $id, &$key = null) {
foreach( $items as $item ) {
if( $item->id == $id ) {
$key = key($item);
return $item;
break;
}
}
return null;
}
Usage
$item = search($items, 4, $key);
unset($items[$key]);
Note: This could be modified to allow a custom key and return multiple items that share the same value.
I've created an example so you can see it in action.
A funny alternative
$getIdUnset = function($id) use ($myArray)
{
foreach($myArray as $key => $obj) {
if ($obj->id == $id) {
return $key;
}
}
return false;
};
if ($unset = $getIdUnset(4)) {
unset($myArray[$unset]);
}
Currently php does not have any supported function for this yet.
So refer to Java's Vector, or jQuery's $.inArray(), it would simply be:
public function indexOf($object, array $elementData) {
$elementCount = count($elementData);
for ($i = 0 ; $i < $elementCount ; $i++){
if ($object == $elementData[$i]) {
return $i;
}
}
return -1;
}
You can save this function as a core function for later.
In my case, this my array as $array
I was confused about this problem of my project, but some answer here helped me.
array(3) {
[0]=> float(-0.12459619130796)
[1]=> float(-0.64018439966448)
[2]=> float(0)
}
Then use if condition to stop looping
foreach($array as $key => $val){
if($key == 0){ //the key is 0
echo $key; //find the key
echo $val; //get the value
}
}
I know, after so many years this could be a useless answer, but why not?
This is my personal implementation of a possible index_of using the same code as other answers but let the programmer to choose when and how the check will be done, supporting also complex checks.
if (!function_exists('index_of'))
{
/**
* #param iterable $haystack
* #param callable $callback
* #param mixed|null &$item
* #return false|int|string
*/
function index_of($haystack, $callback, &$item = null)
{
foreach($haystack as $_key => $_item) {
if ($callback($_item, $_key) === true) {
$item = $_item;
return $_key;
}
}
return false;
}
}
foreach( $arr as $k=>&$a) {
if( $a['id'] == 4 )
unset($arr[$k]);
}

PHP find value in multidimensional / nested array

I've trawled the site and the net and have tried various recursive functions etc to no avail, so I'm hoping someone here can point out where I'm going wrong :)
I have an array named $meetingArray with the following values;
Array (
[0] => Array (
[Meet_ID] => 9313
[Meet_Name] => 456136
[Meet_CallInNumber] =>
[Meet_AttendeeCode] =>
[Meet_Password] =>
[Meet_ScheduledDateTime] => 2011-07-18 16:00:00
[Meet_ModeratorCode] =>
[Meet_RequireRegistration] => 0
[Meet_CurrentUsers] => 0
)
[1] => Array (
[Meet_ID] => 9314
[Meet_Name] => 456120
[Meet_CallInNumber] =>
[Meet_AttendeeCode] =>
[Meet_Password] =>
[Meet_ScheduledDateTime] => 2011-07-18 16:00:00
[Meet_ModeratorCode] =>
[Meet_RequireRegistration] => 0
[Meet_CurrentUsers] => 0
)
)
I also have a variable named $meetID.
I want to know if the value in $meetID appears in [Meet_Name] within the array and simply evaluate this true or false.
Any help very much appreciated before I shoot myself :)
function multi_in_array($needle, $haystack, $key) {
foreach ($haystack as $h) {
if (array_key_exists($key, $h) && $h[$key]==$needle) {
return true;
}
}
return false;
}
if (multi_in_array($meetID, $meetingArray, 'Meet_Name')) {
//...
}
I am unsure what you mean by
$meetID appears in [Meet_Name]
but simply substitute the $h[$key]==$needle condition with something that meets your needs.
For single-dimensional arrays you can use array_search(). This can be adapted for multi-dimensional arrays like so:
function array_search_recursive($needle, $haystack, $strict=false, $stack=array()) {
$results = array();
foreach($haystack as $key=>$value) {
if(($strict && $needle === $value) || (!$strict && $needle == $value)) {
$results[] = array_merge($stack, array($key));
}
if(is_array($value) && count($value) != 0) {
$results = array_merge($results, array_search_recursive($needle, $value, $strict, array_merge($stack, array($key))));
}
}
return($results);
}
Write a method something like this:
function valInArr($array, $field, $value) {
foreach ($array as $id => $nestedArray) {
if (strpos($value,$nestedArray[$field])) return $id;
//if ($nestedArray[$field] === $value) return $id; // use this line if you want the values to be identical
}
return false;
}
$meetID = 1234;
$x = valInArr($array, "Meet_Name", $meetID);
if ($x) print_r($array[$x]);
This function will evaluate true if the record is found in the array and also enable you to quickly access the specific nested array matching that ID.

How to find an array from parent array?

I am using below code to find an array inside parent array but it is not working that is retuning empty even though the specified key exits in the parent array
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$cards = array();
foreach($cards_parent as $key => $card)
{
if ($key === 'Cards')
{
$cards[] = $cards_parent[$key];
break;
}
}
Do you know any array function that will search parent array for specified key and if found it will create an array starting from that key?
you want array_key_exists()
takes in a needle (string), then haystack (array) and returns true or false.
in one of the comments, there is a recursive solution that looks like it might be more like what you want. http://us2.php.net/manual/en/function.array-key-exists.php#94601
here you can use recursion:
function Recursor($arr)
{
if(is_array($arr))
{
foreach($arr as $k=>$v)
{
if($k == 'Cards')
{
$_GLOBAL['cards'][] = $card;
} else {
Recursor($arr[$k]);
}
}
}
}
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$_GLOBAL['cards'] = array();
Recursor($cards_parent);
Could you please put a print_r($feedData) up? I ran the below code
<?php
$feedData = array('BetradarLivescoreData' => array('Sport' => array('Category' => array('Tournament' => array('Match' => array('Cards' => array('hellow','jwalk')))))));
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$cards = array();
foreach($cards_parent as $key => $card)
{
if ($key === 'Cards')
{
$cards[] = $card;
break;
}
}
print_r($cards);
And it returned a populated array:
Array ( [0] => Array ( [0] => hellow [1] => jwalk ) )
So your code is correct, it may be that your array $feedData is not.

Extract leaf nodes of multi-dimensional array in PHP

Suppose I have an array in PHP that looks like this
array
(
array(0)
(
array(0)
(
.
.
.
)
.
.
array(10)
(
..
)
)
.
.
.
array(n)
(
array(0)
(
)
)
)
And I need all the leaf elements of this mulit-dimensional array into a linear array, how should I go about doing this without resorting recursion, such like this?
function getChild($element)
{
foreach($element as $e)
{
if (is_array($e)
{
getChild($e);
}
}
}
Note: code snippet above, horribly incompleted
Update: example of array
Array
(
[0] => Array
(
[0] => Array
(
[0] => Seller Object
(
[credits:private] => 5000000
[balance:private] => 4998970
[queueid:private] => 0
[sellerid:private] => 2
[dateTime:private] => 2009-07-25 17:53:10
)
)
)
...snipped.
[2] => Array
(
[0] => Array
(
[0] => Seller Object
(
[credits:private] => 10000000
[balance:private] => 9997940
[queueid:private] => 135
[sellerid:private] => 234
[dateTime:private] => 2009-07-14 23:36:00
)
)
....snipped....
)
)
Actually, there is a single function that will do the trick, check the manual page at: http://php.net/manual/en/function.array-walk-recursive.php
Quick snippet adapted from the page:
$data = array('test' => array('deeper' => array('last' => 'foo'), 'bar'), 'baz');
var_dump($data);
function printValue($value, $key, $userData)
{
//echo "$value\n";
$userData[] = $value;
}
$result = new ArrayObject();
array_walk_recursive($data, 'printValue', $result);
var_dump($result);
You could use iterators, for example:
$result = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::LEAVES_ONLY) as $value) {
$result[] = $value;
}
Use a stack:
<?php
$data = array(array(array("foo"),"bar"),"baz");
$results = array();
$process = $data;
while (count($process) > 0) {
$current = array_pop($process);
if (is_array($current)) {
// Using a loop for clarity. You could use array_merge() here.
foreach ($current as $item) {
// As an optimization you could add "flat" items directly to the results array here.
array_push($process, $item);
}
} else {
array_push($results, $current);
}
}
print_r($results);
Output:
Array
(
[0] => baz
[1] => bar
[2] => foo
)
This should be more memory efficient than the recursive approach. Despite the fact that we do a lot of array manipulation here, PHP has copy-on-write semantics so the actual zvals of the real data won't be duplicated in memory.
Try this:
function getLeafs($element) {
$leafs = array();
foreach ($element as $e) {
if (is_array($e)) {
$leafs = array_merge($leafs, getLeafs($e));
} else {
$leafs[] = $e;
}
}
return $leafs;
}
Edit   Apparently you don’t want a recursive solution. So here’s an iterative solution that uses a stack:
function getLeafs($element) {
$stack = array($element);
$leafs = array();
while ($item = array_pop($stack)) {
while ($e = array_shift($item)) {
if (is_array($e)) {
array_push($stack, array($item));
array_push($stack, $e);
break;
} else {
$leafs[] = $e;
}
}
}
return $leafs;
}
Just got the same issue and used another method that was not mentioned. The accepted answer require the ArrayObject class to work properly. It can be done with the array primitive and the use keyword in the anonymous function (PHP >= 5.3):
<?php
$data = array(
array(1,2,3,4,5),
array(6,7,8,9,0),
);
$result = array();
array_walk_recursive($data, function($v) use (&$result) { # by reference
$result[] = $v;
});
var_dump($result);
There is no flatten function to get directly the leafs. You have to use recursion to check for each array if has more array children and only when you get to the bottom to move the element to a result flat array.

Categories