How to find object in php array and delete it? - php

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

Related

PHP object to array sorting by associative key

Good morning, I'm just shook about it but, php has more than 10 ways to sort an array but I can't find one to sort by desired key dynamically.
I cannot set something like some uksorts because it will be filled dynamically. I'm using smarty on the front (which does not have array sort functions) and I'm trying to make a callable static to resort and print sorted arrays on one specific point.
I've applied some logic on it and I think it would be something like this.
Smarty:
{assign var='key' value='category_id'}
{assign var='direction' value='normal'}
{assign var='sortedItem' value=''}
{foreach $object.prop item="item"}
{sortedItem = Class::arraySortBy($item, $key, $direction)}
<a href="{$item['link']}">
{$item['name']}
</a>
{foreach}
PHP:
public static function arraySortBy($elemGroup, $sortBy, $direction) {
if(is_object($elemGroup)){
$elemGroup = (array) $elemGroup;
}
if ($direction == 'normal') {
// here is where i want to sort the elemGroup array by the key i want, as the key is product_id and i want to sort by category_id
} else if ($direction == 'reverse'){
// here the same but in reverse order
} else {
error_log('Direction not properly set.');
}
return $elemGroup;
}
the fact is that i want to re-order the objects bu category_id, and second by product_id IE:
itemA{product_id=1, category_id=1}
itemB{product_id=2, category_id=2}
itemC{product_id=3, category_id=1}
itemE{product_id=4, category_id=1}
itemD{product_id=5, category_id=2}
Result:
itemA
itemB
itemC
itemE
itemD
expected result
itemA
itemC
itemE
itemB
itemD
Is there a way to make this with PHP sorting functions or it has to be custom?
Thanks
Why can't you use uasort?
function custom_array_sort($arr, $sorts)
{
// Either pass an array of sorts, or every argument after the first one.
$sorts = is_array($sorts) ? $sorts : array_slice(func_get_args(), 1);
uasort($arr, function ($a, $b) use (&$arr, $sorts) {
for ($i = 0; $i < count($sorts); $i++) {
if ($a[$sorts[$i]] == $b[$sorts[$i]]) {
if (isset($sorts[$i + 1])) {
$arr = custom_array_sort($arr, array_slice($sorts, 1));
} else {
return 0;
}
} else {
return $a[$sorts[$i]] - $b[$sorts[$i]];
}
}
});
return $arr;
}
Live demo
This works by first comparing the category_id fields.
If these are the same then we compare the product_id. The subtraction is used so that the smaller of the product_ids is sorted before the bigger one.
If the category_ids are not the same then we do the same operation on the category_ids as we did above for product_id.
To implement this into your view, follow this documentation
$smarty->register_function('custom_array_sort', 'custom_array_sort_wrapper');
function custom_array_sort_wrapper($params, &$smarty)
{
if (empty($params['arr'])) {
$arr = [];
} else {
$arr = $params['arr'];
}
if (empty($params['sorts'])) {
$sorts = [];
} else {
$sorts = $params['sorts'];
}
return custom_array_sort($arr, $sorts);
}
This can then be used in your views in the following way:
{custom_array_sort arr=$object sorts=['category_id', 'product_id']}
The advantage of this new implementation is that you can specify as many columns to sort as you like.
It also means that you can specify different columns to sort for different arrays.
If you want to sort by more columns then just add another column name to the $sorts array.
You can you try this function.
function array_sort($array, $on, $order=SORT_ASC){
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
Example:
Array Value:-
$item_array = array (
'itemA' => array('product_id'=>1, 'category_id'=>1),
'itemB' => array('product_id'=>2, 'category_id'=>2),
'itemC' => array('product_id'=>3, 'category_id'=>1),
'itemD' => array('product_id'=>4, 'category_id'=>1),
'itemE' => array('product_id'=>5, 'category_id'=>2)
);
Use function:-
$itme_list = array_sort($item_array, 'category_id', SORT_ASC);
print_r($itme_list);
Output:
Array
(
[itemA] => Array
(
[product_id] => 1
[category_id] => 1
)
[itemC] => Array
(
[product_id] => 3
[category_id] => 1
)
[itemD] => Array
(
[product_id] => 4
[category_id] => 1
)
[itemB] => Array
(
[product_id] => 2
[category_id] => 2
)
[itemE] => Array
(
[product_id] => 5
[category_id] => 2
)
)
Note: Reference link :-
Sort PHP multi-dimensional array based on key?
How to sort multidimensional array by multiply keys?

Modifying N-dimensional array PHP

how can I add an extra dimesion before each element in N-dimensional array (recursively)? Let's say I have
Array
(
[room] => Array
(
[bed] = Array
(
[material] => wood
)
)
)
And I want to add an extra "[0]" dimension before room, bed and material. (Adding dimension only if the last element is an array). I also want to distinguish, if there already is the extra [0] dimension, so it will not appear twice .. + I don't want to add [0] if the array key is named "#attribute".
I'm trying to figure it out, but I'm really lost. This is what I've got so far..
function normalize_array (&$array) {
if (is_array($array)) {
if (!isset($array[0])) {
$array = array ( "0" => $array);
}
foreach ($array[0] as $next) {
normalize_array ($next);
}
}
}
but it does not work recursively. Any help will be appreciated. Thanks!
From the documentation of foreach:
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 if you modify your function like this, it works:
function normalize_array (&$array) {
if (is_array($array)) {
if (!isset($array[0])) {
$array = array ( "0" => $array);
}
foreach ($array[0] as &$next) { // <-- add & here
normalize_array ($next);
}
}
}
Possible solution (tested just a little, but seems to work):
function normalize_array($array, $keys){
$new = array();
foreach($array as $key => $value){
if (in_array($key, $keys) && is_array($value)){
$new["0"] = array($key => normalize_array($value, $keys));
} else {
$new[$key] = $value ;
}
}
return $new ;
}
$data = array(
"room" => array(
"bed" => array(
"material" => "wood"
)
)
);
$keys = array("room", "bed", "material");
$new = normalize_array($data, $keys);
var_dump($new);
Final solution:
function normalize_array_rec (&$array) {
if (is_array($array)) {
if (!isset($array[0])) {
$array = array ( "0" => $array);
}
$i = 0;
while (isset($array[$i])) {
foreach ($array[$i] as &$next) {
normalize_array_rec ($next);
}
$i++;
}
}
}
Forgot to call function in each instance of array, not only in [0] index.

PHP: Count the appearance of particular value in array

I am wondering if I could explain this.
I have a multidimensional array , I would like to get the count of particular value appearing in that array
Below I am showing the snippet of array . I am just checking with the profile_type .
So I am trying to display the count of profile_type in the array
EDIT
Sorry I've forgot mention something, not something its the main thing , I need the count of profile_type==p
Array
(
[0] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => p
[birthyear] => 1978
[is_elite] => 0
)
)
[1] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => d
[birthyear] => 1972
[is_elite] => 1
)
)
)
Easy solution with RecursiveArrayIterator, so you don't have to care about the dimensions:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$counter = 0
foreach ($iterator as $key => $value) {
if ($key == 'profile_type' && $value == 'p') {
$counter++;
}
}
echo $counter;
Something like this might work...
$counts = array();
foreach ($array as $key=>$val) {
foreach ($innerArray as $driver=>$arr) {
$counts[] = $arr['profile_type'];
}
}
$solution = array_count_values($counts);
I'd do something like:
$profile = array();
foreach($array as $elem) {
if (isset($elem['Driver']['profile_type'])) {
$profile[$elem['Driver']['profile_type']]++;
} else {
$profile[$elem['Driver']['profile_type']] = 1;
}
}
print_r($profile);
You may also use array_walk($array,"test") and define a function "test" that checks each item of the array for 'type' and calls recursively array_walk($arrayElement,"test") for items of type 'array' , else checks for the condition. If condition satisfies, increment a count.
Hi You can get count of profuke_type==p from a multi dimensiona array
$arr = array();
$arr[0]['Driver']['id'] = 4;
$arr[0]['Driver']['profile_type'] = 'p';
$arr[0]['Driver']['birthyear'] = 1978;
$arr[0]['Driver']['is_elite'] = 0;
$arr[1]['Driver']['id'] = 4;
$arr[1]['Driver']['profile_type'] = 'd';
$arr[1]['Driver']['birthyear'] = 1972;
$arr[1]['Driver']['is_elite'] = 1;
$arr[2]['profile_type'] = 'p';
$result = 0;
get_count($arr, 'profile_type', 'd' , $result);
echo $result;
function get_count($array, $key, $value , &$result){
if(!is_array($array)){
return;
}
if($array[$key] == $value){
$result++;
}
foreach($array AS $arr){
get_count($arr, $key, $value , $result);
}
}
try this..
thanks

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