Replace array keys with another value - php

I have an array which looks like this:
[0] => stdClass Object
(
[id] => 152
[type_id] => 5
[name] => test 1
)
[1] => stdClass Object
(
[id] => 153
[type_id] => 8
[name] => test 2
)
[2] => stdClass Object
(
[id] => 154
[type_id] => 13
[name] => test 3
)
Is there any way I can transform it into the array below?
[5] => stdClass Object
(
[id] => 152
[name] => test 1
)
[8] => stdClass Object
(
[id] => 153
[name] => test 2
)
[13] => stdClass Object
(
[id] => 154
[name] => test 3
)
Basically I changed the array key with the type_id value.

You should be able to unset the stdClass's properties as follows:
$newObject = array();
foreach ($oldObject as $object) {
$typeID = $object->type_id;
$newObject[$typeID] = $object;
unset($newObject[$typeID]->type_id);
}
This will iterate through your array of stdClass objects and save the entry into a new array. Afterwards, the property type_id will be deleted.

Pass it into a function that returns a new array:
function convert($arr)
{
$new_arr = array();
for ($i = 0; $i < count($arr); $i++)
{
$id = $arr[$i]['type_id'];
unset($arr[$i]['type_id']);
$new_arr[$id] = $arr[$i];
}
return $new_arr;
}

To replace a value, simply use: http://php.net/manual/en/function.unset.php and to add another value: http://php.net/manual/en/function.array-push.php

Related

How to merge three arrays according to common key in php

I have three arrays first array include ids and employees name and second array have monthly collection with employee ids and third array have daily collection with employee id and daily collection I want to merge these array with ids and name and dcollection and monthly collection but the desired output is not coming here my first array $ids is
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Rohit
)
[1] => stdClass Object
(
[id] => 2
[name] => Emop1
)
[2] => stdClass Object
(
[id] => 3
[name] => Pankaj
)
[3] => stdClass Object
(
[id] => 4
[name] => tejpal singh
)
)
second array $q1 is
Array
(
[0] => stdClass Object
(
[name] => Rohit
[id] => 1
[mcollecton] => 100
)
[1] => stdClass Object
(
[name] => Emop1
[id] => 2
[mcollecton] => 1222
)
)
third array $q2 is
Array
(
[0] => stdClass Object
(
[name] => Rohit
[id] => 1
[dcollecton] => 300
)
[1] => stdClass Object
(
[name] => Emop1
[id] => 2
[dcollecton] => 150
)
)
so far what I have tried
$new_array = array();
foreach($ids as $k) {
$q1n = array("id"=>$k->id,"name"=>$k->name);
foreach($q1 as $k1) {
if($k->id==$k1->id){
$mc = array("mc"=>$k1->mcollecton);
array_merge($q1n,$mc);
}
}
foreach($q2 as $k1){
if($k->id==$k1->id){
$dc = array("dc"=>$k1->dcollecton);
array_merge($q1n,$dc);
}
}
$a = array_merge($q1n,$mc);
$av = array_merge($q1n,$dc);
array_push($new_array,$q1n);
}
but the output is coming as
Array
(
[0] => Array
(
[id] => 1
[name] => Rohit
)
[1] => Array
(
[id] => 2
[name] => Emop1
)
[2] => Array
(
[id] => 3
[name] => Pankaj
)
[3] => Array
(
[id] => 4
[name] => tejpal singh
)
)
I want the output be like
Array
(
[0] => Array
(
[id] => 1
[name] => Rohit
[mcollection] => 100
[dcollection] => 300
)
[1] => Array
(
[id] => 2
[name] => Emop1
[mcollection] => 1222
[dcollection] => 150
)
[2] => Array
(
[id] => 3
[name] => Pankaj
[mcollection] => 0
[dcollection] => 0
)
[3] => Array
(
[id] => 4
[name] => tejpal singh
[mcollection] => 0
[dcollection] => 0
)
)
So I have tried many times but the desired output is not coming . please help me out how to get the desired output.
It seemed like that answer could be modified, or put in a function that you could call multiple times if needed to combine more than two arrays.
There's probably cleaner ways to handle this with array functions like array_merge or array_walk, but this is the general idea of how I might approach it. I haven't tested this, but maybe it's useful.
foreach($first as $key1 => $value){
foreach($second as $key2 => $value2){
// match the ids and check if array key exists on first array
if($value['id'] === $value2['id'] && empty($first[$key2])){
$first[$key][$key2] = $value2;
}
}
}
EDIT: Based on the answer you posted vs the question you asked, are you incrementing the collection numbers or just setting them? In other words why use +=? You should also be able to remove array_merge and array_push.
Below is geared more towards what you're trying to do. I haven't tested this either, but if you run into errors, post your code with the errors returned so that it's easier to debug:
foreach($ids as $k)
{
$thisArray = $newArray[] = array("id"=>$k->id,"name"=>$k->name);
foreach($q1 as $k1)
{
if($k->id == $k1->id && !empty($k1->mcollecton))
{
$thisArray['mc'] = $k1->mcollecton;
}
}
foreach($q2 as $k2)
{
if($k->id == $k2->id && !empty($k2->dcollecton))
{
$thisArray['dc'] = $k2->dcollecton;
}
}
}
// This should have both new collections fields on all array items
print_r($newArray)

get stdclass object array cat_id value?

How to get cat_id ?
Array
(
[0] => stdClass Object
(
[id] => 17
[res_id] => 10
[cat_id] => 3
)
[1] => stdClass Object
(
[id] => 18
[res_id] => 10
[cat_id] => 4
)
[2] => stdClass Object
(
[id] => 52
[res_id] => 19
[cat_id] => 1
)
[3] => stdClass Object
(
[id] => 53
[res_id] => 19
[cat_id] => 3
)
[4] => stdClass Object
(
[id] => 54
[res_id] => 19
[cat_id] => 4
)
I want cat_id from all stdClass Object array.
how can i get this ?
Can anyone help me how do I retrieve the value of cat_id?
Thanks.
Try this
$Your_array
foreach($Your_array AS $Cat){
echo $Cat->cat_id;
}
You can use array_map. For example, if your source array is $array:
$result = array_map(function($x){
return $x->cat_id;
}, $array);
print_r($result);
That will give you:
Array
(
[0] => 3
[1] => 4
[2] => 1
[3] => 3
[4] => 4
)
Demo
$array = array();
$object = new stdClass;
$object->id= "ID";
$object->res_id = "RES_ID";
$object->cat_id = "CAT_ID";
$array[] = $object;
To Access to object attribute:
echo $array[0]->cat_id;
You can replace 0 with index and iterate it in array:
for($index=0;$index<count($array);$index++){
if(isset($array[$index]->cat_id)){
// Do something...
}
}
Object properties in PHP are accessed using the -> syntax. To get the cat_id property of each item in the array, you could loop through the array to get each item one by one, and store the cat_id property of the objects in a new array, like so:
$cat_ids = array();
foreach($array as $item){
$cat_ids[] = $item->cat_id;
}
print_r($cat_ids);
Gives:
Array
(
[0] => 3
[1] => 4
[2] => 1
[3] => 3
[4] => 4
)
If you don't need all the cat_ids, but just the one for a specific object in your original array, you can use
$array[2]->cat_id;
Which would get the cat_id property of the 3rd item in your array.

PHP - Merge 2 arrays of object using a key/id

I want to merge the 2 arrays of objects based on the 'id' field of Array1 and the 'itemVendorCode' of Array2. I also wanted to remove from the resulting arrays of object anything that didn't match.
Array1:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 89-575-2354
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 230.35
)
)
Array2:
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 was able to solve this by this code:
$indexed = array();
foreach($itemsArray as $value) {
$indexed[$value->itemVendorCode] = $value;
}
$results = array();
foreach($vendorItems as $obj) {
$value = $indexed[$obj->id];
if (isset($value)) {
foreach($value as $name => $val) {
$obj->$name = $val;
array_push($results, $obj);
}
}
}
print_r($results);
credits to the original poster. I just modified it a bit,
I was able to get the result like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[1] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[2] => stdClass Object
(
[id] => 14-102-1010
[qty] => 16
[price] => 3.2
[internalId] => 57033
[itemVendorCode] => 14-102-1010
)
)
I think you will have to use array_map function which provides you a callback function to execute on array(s).
In the callback function:
- declare your array1
- foreach the second array
- set an if statement to check that the current iteration with the id value matches the itemVendorCode of the array2 and return it
something like this:
// You have to specify to PHP to use a local copy of your $array2 to works with it into your callback
$cb = function ($obj1) use ($array2)
{
// you foreach this array
foreach ($array2 as $obj2) {
// if the value of id matches itemVendorCode
if ($obj1->id === $obj2->itemVendorCode) {
// you return the id
return $obj->id;
}
}
};
// this function will fill a new array with all returned data
$mergedArray = array_map($cb, $array1);
This code is a sample but doesn't provide you, your needled solution, try to update it to do what you exactly want ;)

Count occurrences of a value in a column of an array of object arrays

Does anyone know how to count the occurrences of "photo" in this array:
Array (
[0] => stdClass Object ( [type] => photo [id] => 1404781893036 [created_time] => 2012-03-02T07:58:23+0000 )
[1] => stdClass Object ( [type] => photo [id] => 14047818930362 [created_time] => 2012-03-01T14:58:53+0000 )
[2] => stdClass Object ( [type] => status [id] => 1404781893036 [created_time] => 2012-03-01T09:49:40+0000 )
[3] => stdClass Object ( [type] => status [id] => 14047818930362 [created_time] => 2012-03-01T09:36:04+0000 )
[4] => stdClass Object ( [type] => photo [id] => 14047818930362 [created_time] => 2012-02-28T07:03:25+0000 )
[5] => stdClass Object ( [type] => photo [id] => 1404781893036 [created_time] => 2012-02-27T09:15:34+0000 )
[6] => stdClass Object ( [type] => photo [id] => 14047818930362 [created_time] => 2012-02-27T07:32:13+0000 )
[7] => stdClass Object ( [type] => status [id] => 1404781893036 [created_time] => 2012-02-25T09:36:57+0000 )
[8] => stdClass Object ( [type] => photo [id] => 1404781893036 [created_time] => 2012-02-23T08:46:43+0000 )
[9] => stdClass Object ( [type] => status [id] => 1404781893036 [created_time] => 2012-02-22T21:04:30+0000 )
[10] => stdClass Object ( [type] => status [id] => 1404781893036 [created_time] => 2012-02-21T20:38:27+0000 )
[11] => stdClass Object ( [type] => photo [id] => 1404781893036 [created_time] => 2012-02-21T07:22:44+0000 )
[12] => stdClass Object ( [type] => status [id] => 14047818930362 [created_time] => 2012-02-20T08:32:46+0000 )
[13] => stdClass Object ( [type] => status [id] => 1404781893036 [created_time] => 2012-02-17T15:00:11+0000 ) )
To count matching occurance of a string in multidimensional array you will need to iterate over each array element and match the string and increment the count. Similiarly #Dor has suggested
$count = 0;
foreach ($array as $item) {
if ($item->type === 'photo') {
$count++;
}
}
If you want achieve same in single dimensional array then It's pretty straightforward. You can use array_count_values PHP array function as explained below.
<?php
$array = array(1, "test", 1, "php", "test");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[test] => 2
[php] => 1
)
$count = 0;
foreach ($array as $item) {
if ($item->type === 'photo') {
$count++;
}
}
I'd like to acknowledge that the method by Dor Shemer is (IMO) the most direct, clean, readable, and reliable method. I just want to offer a few alternatives for those who prefer to use functional programming ...array_reduce() is a close second for me. Finally, I want to pinpoint a small gotcha for methods that use array_count_values() -- please read on...
Battery of Methods: (Demo)
$photo_count=0; // establish default value
foreach($array as $objects){
if($objects->type==='photo') ++$photo_count; // pre-increment
}
echo "foreach result = $photo_count";
echo "array_reduce = ",array_reduce($array,function($carry,$objects){return $carry+($objects->type==='photo'?1:0);},0);
echo "array_filter & count = ",sizeof(array_filter($array,function($objects){return $objects->type==='photo';}));
echo "array_column & array_filter & count = ",sizeof(array_filter(array_column($array,'type'),function($v){return $v==='photo';}));
echo "array_map & array_count_values & array_replace = ",array_replace(['photo'=>0],array_count_values(array_map(function($o) {return $o->type;}, $array)))['photo'];
echo "array_map & array_count_values (gives Notice) = ",array_count_values(array_map(function($o) {return $o->type;}, $array))['photo'];
Input/Output using OP's sample data (no trouble):
$array=[
(object)['type'=>'photo','id'=>1404781893036,'created_time'=>'2012-03-02T07:58:23+0000'],
(object)['type'=>'photo','id'=>14047818930362,'created_time'=>'2012-03-01T14:58:53+0000'],
(object)['type'=>'status','id'=>1404781893036,'created_time'=>'2012-03-01T09:49:40+0000'],
(object)['type'=>'status','id'=>14047818930362,'created_time'=>'2012-03-01T09:36:04+0000'],
(object)['type'=>'photo','id'=>14047818930362,'created_time'=>'2012-02-28T07:03:25+0000'],
(object)['type'=>'photo','id'=>1404781893036,'created_time'=>'2012-02-27T09:15:34+0000'],
(object)['type'=>'photo','id'=>14047818930362,'created_time'=>'2012-02-27T07:32:13+0000'],
(object)['type'=>'status','id'=>1404781893036,'created_time'=>'2012-02-25T09:36:57+0000'],
(object)['type'=>'photo','id'=>1404781893036,'created_time'=>'2012-02-23T08:46:43+0000'],
(object)['type'=>'status','id'=>1404781893036,'created_time'=>'2012-02-22T21:04:30+0000'],
(object)['type'=>'status','id'=>1404781893036,'created_time'=>'2012-02-21T20:38:27+0000'],
(object)['type'=>'photo','id'=>1404781893036,'created_time'=>'2012-02-21T07:22:44+0000'],
(object)['type'=>'status','id'=>14047818930362,'created_time'=>'2012-02-20T08:32:46+0000'],
(object)['type'=>'status','id'=>1404781893036,'created_time'=>'2012-02-17T15:00:11+0000']
];
// output:
foreach result = 7
array_reduce = 7
array_filter & count = 7
array_column & array_filter & count = 7
array_map & array_count_values & array_replace = 7
array_map & array_count_values = 7
Input/Output using data with no photo values (trouble with 2nd array_count_values() method):
$array=[
(object)['type'=>'status','id'=>1404781893036,'created_time'=>'2012-03-01T09:49:40+0000'],
(object)['type'=>'status','id'=>14047818930362,'created_time'=>'2012-03-01T09:36:04+0000'],
(object)['type'=>'status','id'=>1404781893036,'created_time'=>'2012-02-25T09:36:57+0000'],
(object)['type'=>'status','id'=>1404781893036,'created_time'=>'2012-02-22T21:04:30+0000'],
(object)['type'=>'status','id'=>1404781893036,'created_time'=>'2012-02-21T20:38:27+0000'],
(object)['type'=>'status','id'=>14047818930362,'created_time'=>'2012-02-20T08:32:46+0000'],
(object)['type'=>'status','id'=>1404781893036,'created_time'=>'2012-02-17T15:00:11+0000']
];
// or if there are no object rows like: $array=[];
// output:
foreach result = 0
array_reduce = 0
array_filter & count = 0
array_column & array_filter & count = 0
array_map & array_count_values & array_replace = 0
array_map & array_count_values (gives Notice) = <br />
<b>Notice</b>: Undefined index: photo in <b>[...][...]</b> on line <b>43</b><br />
array_count_values() doesn't bother to generate elements with a 0 count.
Try with:
$input = array( /* your data */ );
$count = 0;
foreach ( $input as $value ) {
if ( $value->type == 'photo' ) {
$count++;
}
}

Adding to multidimensional arrays PHP

In my function im storing in $var1 a query from the database of posts. And im storing in $var2 a query from the database of images from the posts. (Each has a key post_id to connect them.)
$var1 will return something like this.
array (
[0] => stdClass Object
(
[post_id] => 210
[post_title] => title
)
[1] => stdClass Object
(
[post_id] => 212
[post_title] => title
)
)
and $var2 will return something like this.
array (
[0] => stdClass Object
(
[post_id] => 210
[post_meta_key] => image
[post_meta_value] => image_value
)
[1] => stdClass Object
(
[post_id] => 212
[post_meta_key] => flag
[post_meta_value] => flag_value
)
[2] => stdClass Object
(
[post_id] => 210
[post_meta_key] => image
[post_meta_value] => image_value
)
[3] => stdClass Object
(
[post_id] => 102
[post_meta_key] => image
[post_meta_value] => image_value
)
)
I would like to create a foreach from $var1 and if $var1[post_id] = $var2[post_id] than $var1 will be edited to something like this
array (
[0] => stdClass Object
(
[post_id] => 210
[post_title] => title
[image] => stdClass Object
(
[0] => image_value
[1] => image_value
)
)
[1] => stdClass Object
(
[post_id] => 212
[post_title] => title
)
)
How can i do this?
foreach ($var1 as &$post1)
{
foreach($var2 as $post2)
{
if ($post1->post_id == $post2->post_id)
{
$post1->image = (object)array(
$post2->post_meta_value
);
}
}
}
Better use arrays instead of objects here:
foreach ($var2 as $key2=>$var2){
if (!empty($var1[$key2])){
$var1[$key2]['image']->$var2;
}
}
You could cast arrays and objects back and forth with
$array = (array)$object;
$object = (object)$array;
This is what you want:
foreach ( $var1 as $v1 )
{
foreach ( $var2 as $v2 )
{
if ( $v1['post_id'] == $v2['post_id'] )
$v1['image'][] = $v2['post_meta_value'];
}
}

Categories