When adding item to array, it overrides the first value - php

For some reason when I try to add an item to my array it overrides the fist item. I can't figure out why it is doing that. The first element should have an id of 1 and the second should be 2 but instead I get 2 and 2.
$array = new stdClass;
$arrays = [];
$ids = [1,2];
foreach ($ids as $id) {
$array->id = $id;
$arrays[] = $array;
print_r($arrays);
}
The result:
Array
(
[0] => stdClass Object
(
[id] => 1
)
)
Array
(
[0] => stdClass Object
(
[id] => 2
)
[1] => stdClass Object
(
[id] => 2
)
)

You are updating the same object, you need to put 2 different objects within the array, bring the class declaration within the loop.
foreach ($ids as $id) {
$array = new stdClass; // object initialization
$array->id = $id;
$arrays[] = $array;
print_r($arrays);
}

Related

Get multidimensional sub array count in php

I have below type of array, now I want to get count of it's subarray
For example I want to get count key 7 & 8. How to do it ? Any solution for that ? I tried but but no success :(
Array
(
[0] => stdClass Object
(
[id] => 4
[Blogdata] => stdClass Object
(
[7] => Array
(
[0] => stdClass Object
(
[blog_id] => 105
)
)
[8] => Array
(
[0] => stdClass Object
(
[blog_id] => 101
)
)
)
)
)
$date_count = array();
foreach($FeaturedBlogs as $Key=>$date) {
foreach($date as $d) {
$key = array_keys($d); // get our date
// echo $key;echo "<br>";
print_r($d);
$date_count[$key[0]]++;
}
}
Try this....
//Count Sub Array
$final_array = [];
$x = 0;
function countSubArray($data)
{
global $final_array;
global $x;
foreach($data as $key)
{
if(is_array($key))
{
$final_array[$x][0] = "1";
$final_array[$x][1] = json_encode($key);
$final_array[$x][2] = count((array)$key);
$x++;
countSubArray($key);
}
if(is_object($key))
{
$final_array[$x][0] = "2";
$final_array[$x][1] = json_encode($key);
$final_array[$x][2] = count((array)$key);
$x++;
countSubArray($key);
}
}
}
// Call Function...
countSubArray($arr); // what array you count..
// Display Sub Array Count...
$t_count = 0;
foreach($final_array as $d)
{
if($d[0] == 1)
{
echo "Array Count :".$d[2]." Array : ".$d[1]."<br>";
$t_count++;
}
}
echo "Total Array Count :".$t_count;
output of this example is...
Array
(
[0] => stdClass Object
(
[id] => 4
[Blogdata] => stdClass Object
(
[7] => Array
(
[0] => stdClass Object
(
[blog_id] => 135
)
)
[8] => Array
(
[0] => stdClass Object
(
[blog_id] => 101
)
)
)
)
)
Array Count :1 Array : [{"blog_id":135}]
Array Count :1 Array : [{"blog_id":101}]
Total Array Count :2
Updated Answer
This is going to use a function as it's own callback function. The function will loop through an object or an array and test each element to see if it is another object or array.
If it did find a new object or array, then the function calls itself again to perform the same operations on the element, effectively traversing through your entire array.
When it has found the bottom of each element it will return the value of the counter which was keeping track of how many arrays it came across.
Like so:
function arrayCounter($data){
//At this point we have an array or an object.
//Lets loop across the elements and see if we have any more nested arrays or objects.
foreach($data as $key){
$count = 0;
//Test each element to see if it's an object or an array.
if(is_array($key) || is_object($key)){
//If it is we are going to send the element through another instance of the function.
$count += arrayCounter($key);
}
//If the element is an array we are going to increment the counter.
if(is_array($key)){
$count++;
}
}
return $count;
}
$count = arrayCounter($data);
echo 'Count: ' . $count; //Using your data this will return "2".
Hope it helps!

Append new key to an existing array in an object

I have an existing JSON array:
stdClass Object
(
[set] => Array
(
[0] => stdClass Object
(
[name] => agenda
)
[1] => stdClass Object
(
[name] => first aid
)
)
)
I need to add a new key to it, so the final JSON result is something like this:
set: [{
name: 'agenda',
value: 'Agenda'
}, {
code: 'first aid',
value: 'First Aid'
}],
This is what I've done so far:
$result = array();
foreach ($data->set as $k => $row) {
$result['name'][$k] = $row->name;
$result['value'][$k] = ucwords($row->name);
}
But I have ended up with:
Array
(
[name] => Array
(
[0] => agenda
[1] => aid kit
)
[value] => Array
(
[0] => Agenda
[0] => First Aid
)
)
How can I merge the above so the name and value keys are in pair rather then being separate?
Update $row directly to modify your existing $data:
foreach ($data->set as $row) {
$row->value = ucwords($row->name);
}
To do it the way you are attempting:
$result = $data;
foreach ($data->set as $k => $row) {
$result->set[$k]->value = ucwords($row->name);
}
Notice, $row is an object.
Your try this
$result = array();
$count = 0;
foreach ($data->set as $k => $row) {
$result[$count]['name'] = $row->name;
$result[$count]['value'] = ucwords($row->name);
$count++;
}
result this
Array
(
[0] => stdClass Object
(
[name] => agenda
[value] => Agenda
)
[1] => stdClass Object
(
[name] => first aid
[value] => First Aid
)
)
If you want to modify your existing object, you can just set the value property directly.
foreach ($data->set as $row) {
$row->value = ucwords($row->name);
}
If you want to create a result without modifying your original object or leaving references to its internal objects, you can clone each of the internal objects and add the new properties to the cloned objects.
$result = array();
foreach ($data->set as $k => $row) {
$obj = clone $row;
$obj->value = ucwords($row->name);
$result[$k] = $obj;
}

PHP stdClass issue

I try to create an generic object which needs to be structuered like this:
[Content] => stdClass Object
(
[item] => Array
(
[0] => stdClass Object
(
[Value] => STRING
)
)
[item] => Array
(
[0] => stdClass Object
(
[Value] => ANOTHER STRING
)
)
)
This is my code:
$content = new stdClass();
$data = file('filname.csv');
foreach($data as $key => $val) {
$content->item->Value = $val;
}
This overwrites itself each time the loop iterates. By defining item as an array like this:
$content->item = array();
...
$content->item[]->Value = $val;
...the result is also not the estimated.
You are overwritting data each time even using array. You should create temporary object for storing value and then put them to item array.
$content = new \stdClass();
$content->item = array();
foreach($data as $key => $val) {
$itemVal = new \stdClass();
$itemVal->Value = $val;
$content->item[] = $itemVal;
}

How get a object by id from arrays of object?

Assuming that I have an array of objects like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 26-295-1006
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 12-330-1000
[qty] => 2
[price] => 230.35
)
And I have another array of object hat looks like this:
Array
(
[0] => Item Object
(
[internalId] => 14062
[itemVendorCode] => 89-605-1250
)
[1] => Item Object
(
[internalId] => 33806
[itemVendorCode] => 89-575-2354
)
[2] => Item Object
(
[internalId] => 64126
[itemVendorCode] => 26-295-1006
)
)
I want to loop through the 2nd array of objects and get the 'itemVendorCode' and then use it as the 'id' to get the object from the first array of objects. Is there a way to obtain what I want without looping the first array? Looping is very costly in my use-case.
You will have to use loops in any case, even if those loops are hidden within PHP built-in functions.
For instance:
$codes = array_map(function ($item) { return $item->itemVendorCode; }, $array2);
$items = array_filter($array1, function ($item) use ($codes) { return in_array($item->id, $codes); });
// $items contains only elements from $array1 that match on $array2
If this will be more efficient than using regular loops is hard to tell.
Since you are aparently trying to code what is supposed to be a DBMS's job, I recommend you export those tables to a database server such as MySQL instead and let it work its magic on those "JOINs".
Answering your comment, you could merge with something like this:
$result = array();
foreach ($array1 as $item1)
foreach ($array2 as $item2)
if ($item1->id == $item2->itemVendorCode)
$result[] = (object)array_merge((array)$item1, (array)$item2));
$result will contain a new set of objects that merge properties from both $array1 and $array2 where they intersect in id == itemVendorCode.
Do you need first arrays index keys? if not you could iterate throuh first array once and set key to id. Something like:
foreach ($items as $key => $item) {
$items[$item->id] = $item;
unset($items[$key]);
}
Here is another direct approach to solve this problem, even better than the one I proposed earlier:
// you got the $itemVendorCode from looping through the second array, let say :
$itemVendorCode = "89-605-1250";
// I'm assuming that you converted the array of objects in into accessible multidimensional array
// so the $first_array would look like :
$first_array= array (
array (
"id" => "10-423-1176",
"qty" => 2,
"price" => 12.6
),
array (
"id" => "10-423-1176",
"qty" => 5,
"price" => 25
),
array (
"id" => "89-605-1250",
"qty" => 12,
"price" => 30
)
);
// Now you can filter the first array using
$filter = function ($player) use($itemVendorCode) {
return $player ['id'] == $itemVendorCode;
};
$filtered = array_filter ( $first_array, $filter );
// print the price of the matching filtered item
print $filtered[key($filtered)]['price'] ;
You can use the array_map and array_filter() function to achieve that.
Try with this code:
<?php
$first = array();
$first[0] = new stdClass;
$first[0]->id = '89-605-1250';
$first[0]->qty = 2;
$first[0]->price = 12.6;
$first[1] = new stdClass;
$first[1]->id = '89-575-2354';
$first[1]->qty = 24;
$first[1]->price = 230.35;
$last = array();
$last[0] = new stdClass;
$last[0]->internalId = 14062;
$last[0]->itemVendorCode = '89-605-1250';
$last[1] = new stdClass;
$last[1]->internalId = 33806;
$last[1]->itemVendorCode = '89-575-2354';
$ids = array_map(function($element){return $element->itemVendorCode;}, $last);
$to_find = $ids[0];
$object = array_filter($first, function($element){global $to_find; return $element->id == $to_find ? true: false;})[0];
print_r($object);
?>
Output:
stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 12.6
)
try using array_search:
http://php.net/manual/en/function.array-search.php
foreach($array2 as $key=>$item) {
$firstArrayObjectKey = array_search($item['itemVendorCode'], $array1);
//... do something with the key $firstArrayObjectKey
}
In this case you'll need to loop through the first array to get the itemVendorCode.
Right after that you can use the itemValue you got from the previous process to search in a reduced array of the first object using array_reduce function:
http://php.net/manual/en/function.array-reduce.php

PHP Array stdClass Object

I have this array
Array (
[0] => stdClass Object (
[id] => 252062474)
[1] => stdClass Object (
[id] => 252062474)
[3] => stdClass Object (
[id] => 252062474)
)
I need echo all of id's
I tried,
foreach($result as $item) {
echo $item->id;
}
but no luck
I try json_decode()
again no luck I use php 5.5.8
I know this work
echo $item[0]->id;
but i don't how many index is there
any idea?
Maybe you are confused on foreach(). If this works:
echo $item[0]->id;
Then you would need:
foreach($item as $result) {
echo $result->id;
}
Try this-
Code
foreach($result as $p) {
echo $p['id'] . "<br/>";
}
Output
252062474
252062474
252062474
This array could be looped through and data could be retrieved. As you are saying its not working I have added the following code to illustrate how it works right from generating the array for you.
// generating an array like you gave in the example. Note that ur array has same value
// for all the ids in but my example its having different values
$arr = array();
$init = new stdClass;
$init->id = 252062474 ;
$arr[] = $init;
$init = new stdClass;
$init->id = 252062475 ;
$arr[] = $init;
$init = new stdClass;
$init->id = 252062476 ;
$arr[] = $init;
print_r($arr);
The above array is same as yours
Array ( [0] => stdClass Object ( [id] => 252062474 )
[1] => stdClass Object ( [id] => 252062475 )
[2] => stdClass Object ( [id] => 252062476 )
)
Now the following code will loop through and get the data as
foreach($arr as $key=>$val){
echo $key.' ID is :: '.$val->id;
echo '<br />';
}
The output will be
0 ID is :: 252062474
1 ID is :: 252062475
2 ID is :: 252062476
Try this
foreach($result as $item) {
$item = (array)$item;
echo $item['id'];
}

Categories