How to insert item on every item in an array using PHP - php

I have this existing array
Array
(
[0] => stdClass Object
(
[userid] => 1
[user] => John Doe
)
[1] => stdClass Object
(
[userid] => 2
[user] => Mae Smith
)
)
I want to insert new item in each array like [randomNumber] => 50. So the final output must be like this
Array
(
[0] => stdClass Object
(
[userid] => 1
[user] => John Doe
[randomNumber] => 25
)
[1] => stdClass Object
(
[userid] => 2
[user] => Mae Smith
[randomNumber] => 50
)
)
I'm using php using for loop to insert the randomNumber every user
for($i=0 ; $i<count($users) ; $i++) {
// insert randomNumber here
$users[$i] = array('randomNumber' => rand(10,100));
}
It doesn't seems to work. What should be the proper way? Thanks

Iterate with a foreach, and as $user is an object, it will be passed to loop by reference:
foreach ($users as $user) {
$user->randomNumber = rand(10,100);
}

As you have an array of objects rather than arrays...
for($i=0 ; $i<count($users) ; $i++) {
// insert randomNumber here
$users[$i]->randomNumber = rand(10,100);
}

I think foreach function is better for you. and you have array of objects.
foreach ($users as $key => $value) {
$users[$key]->randomNumber = rand(10,100);
}

Related

Taking out just one value from an array

I have an array which is
Array ( [0] => Array ( [picture] => 5a55ed8d8a5c8910913.jpeg
[id] => 1284
[price_range] => Rs 12000 - 9000
[name] => Brown Beauty Office Chair )
[1] => Array ( [picture] => 5a55eefeb9a8e255836.jpeg
[id] => 1285
[price_range] => Rs 8989 - 7000
[name] => Chang Series Office Chair (Grey)
)
)
Now I am fetching the value of id on clicking a remove button, the value I fetch is 1284.
I want to take out just [id]=> 1284 from the above array and then display it using a foreach loop. How I can delete just the [id]=> 1284 without disturbing the other id values and other element.
In the above array I would like to delete one particular id value say just the [id]=> 1284 and keep all other elements intact and as it is.
Any help is welcome.
Use array_search and array_column, to find by id and remove by unset method,
<?php
$array = [
["id"=>123,"desc"=>"test1"],
["id"=>456,"desc"=>"test2"],
["id"=>789,"desc"=>"test3"],
];
$id = 456;
$index = array_search($id, array_column($array, 'id'));
unset($array[$index]);
print_r($array);
?>
Live Demo
Array
(
[0] => Array
(
[id] => 123
[desc] => test1
)
[2] => Array
(
[id] => 789
[desc] => test3
)
)
Since you asked how to achieve it using foreach, I came up with this.
$array = Array (Array ( 'picture' => '5a55ed8d8a5c8910913.jpeg','id' => 1284,'price_range' => 'Rs 12000 - 9000', 'name' => 'Brown Beauty Office Chair'),
Array ( 'picture' => '5a55eefeb9a8e255836.jpeg','id' => 1285,'price_range' => 'Rs 8989 - 7000','name' => 'Chang Series Office Chair (Grey)')
);
foreach($array as $key => $val) {
$id = $array[$key]['id'];
if($id === 1284){
unset($array[$key]['id']);
}
}
print_r($array)
?>
You can also use this too:
<?php
$element_to_remove = 1284;
$i = 0;
foreach($array as $this_arr){
$index = array_search($element_to_remove, $this_arr);
//unset($this_arr[$index]); this formate does not remove element from array
//but below works fine
if(isset($array[$i][$index])){
unset($array[$i][$index]);
}
}
print_r($array);
?>

hierarchial two dimetional php array from an two dimetional php

I have a multiD array containing all users like below.
Array
(
[0] => Array
(
[username] => santoshe62
[sponsor] => santoshe61
)
[1] => Array
(
[username] => santoshe63
[sponsor] => santoshe62
)
[2] => Array
(
[username] => santoshe65
[sponsor] => santoshe64
)
[3] => Array
(
[username] => santoshe67
[sponsor] => santoshe66
)
.............................
)
I want an array from this array containing hierarchical data of given user like below.
Array
(
[0] => Array
(
[username] => santoshe62
[sponsor] => santoshe61
)
[1] => Array
(
[username] => santoshe63
[sponsor] => santoshe62
)
)
I have tried
function parseTree($datas, $parent = 0){
$tree = array();
for($i=0, $ni=count($datas); $i < $ni; $i++){
if($datas[$i]['sponsor'] == $parent){
$tree[] = $datas[$i];
parseTree($datas, $datas[$i]['username']);
}
}
return $tree;
}
Can anybody help me by finding what is wrong in my code? Also please suggest, can I select only this hierarchical structure directly from MySQL? Now I am selecting all results from DB.
The problem is because of this statement in your function, $tree = array();. In each recursive function call, this $tree is getting initialized with an empty array. You have to declare it as static variable, so that it could get initialized only once and could retain its state in recursive function calls.
function parseTree($datas, $parent = 0){
static $tree = array();
...
}

Adding Elements To An StdClass Array - PHP / Codeigniter

I have an array that is an stdClass. The output of that array is as follows :
Array
(
[0] => stdClass Object
(
[vendor_id] => 1
[user_id] => 1
[date_created] => 2013-06-12 16:48:38
[date_edited] =>
[status] => active
[user_firstname] => Stuart
[user_surname] => Blackett
)
)
What I would like to do is add two variables to this stdClass. They are "total_bookings" and "total_venues";
I currently am looping through the results and then getting a count to create the total. I would like to add those two vars to the end of that stdClass array.
My PHP is as follows :
$vendors = $this->po_model->get_all_vendors();
$this->template->set('total_vendors', count($vendors));
$count = 0;
foreach($vendors as $vendor)
{
$count++;
$total_venues = $this->po_model->get_count_venues($vendor->user_id);
$total_bookings = $this->po_model->get_count_bookings($vendor->user_id);
$vendors[$count]['total_venues'] = $total_venues;
$vendors[$count]['total_bookings'] = $total_bookings;
}
However, When I var_dump that my Array looks like this :
Array
(
[0] => stdClass Object
(
[vendor_id] => 1
[user_id] => 1
[date_created] => 2013-06-12 16:48:38
[date_edited] =>
[status] => active
[user_firstname] => Stuart
[user_surname] => Blackett
)
[1] => Array
(
[total_venues] => 6
[total_bookings] => 14
)
)
So my question is, How do I add total_venues and total_bookings to that stdClass()?
Thanks
$myArray[$indexOfObject]->total_venues = 6;
$myArray[$indexOfObject]->total_bookings= 14;
Your example:
foreach($vendors as $key => $vendor)
{
$total_venues = $this->po_model->get_count_venues($vendor->user_id);
$total_bookings = $this->po_model->get_count_bookings($vendor->user_id);
$vendors[$key]->total_venues = $total_venues;
$vendors[$key]->total_bookings = $total_bookings;
}
its an object, you should use object notations, not array notations. also change your move your count++ below these two instructions
$vendors[$count]->total_venues = $total_venues;
$vendors[$count]->total_bookings = $total_bookings;
$count++;

PHP How to Unset Member of Multidimensional Array?

I have a three dimensional array that looks like this
Array(
[Group 1] => Array
(
[0] => Array
(
[category] => Group1
[firstname] => John
[lastname] => Johns
[image] => /mysite.etc/jj.jpg
)
[1] => Array
(
[category] => Group1
[firstname] => John
[lastname] => James
[image] => /mysite.etc/jj2.jpg
)
)
[Group 2] => Array
(
[0] => Array
(
[category] => Group2
[firstname] => John
[lastname] => Jackson
[image] => NULL
)
[1] => Array
(
[category] => Group2
[firstname] => John
[lastname] => Jimson
[image] => /mysite.etc/jj4.jpg
)
)...etc)
I'm trying to loop through the array and remove any people (i.e. the second level of the array) who do not have a value in the [image] cell.
I've tried
foreach($MyArray as $Key=>&$group){
foreach($group as &$staff){
if(!file_exists($staff['image'])){
unset($staff);
}
}
}
but this does not remove the array items with no image. The loop is correctly identifying the staff with no image as if I include a bit of code to echo them onto the page, this works. It's just not unsetting them from the $MyArray array.
Can anyone help me achieve this?
foreach($MyArray as $Key=>$group){
foreach($group as $k=>$staff){
if( !file_exists($staff['image'])) {
unset($MyArray[$Key][$k]);
}
}
}
//you should know the the $group and $staff is temp variables
foreach ($MyArray as $Key=>$group) {
foreach ($group as $k=>$staff) {
if( empty($staff['image']) || !file_exists($staff['image'])) {
unset($MyArray[$key][$k]);
}
}
}
The condition should be following like this.
foreach($MyArray as $Key=>&$group){
foreach($group as $staffkey=>$staff){
if( $staff['image'] == null))
{
unset($MyArray[$key][$staffkey]);
}
}
}
You can use array_filter for this:
With a closure: available in php 5.3
foreach($groups as &$users){
$users = array_filter($users, function ($a) { return isset($a["image"]) && file_exists($a["image"]); });
}
Without closures
function hasImage($a){ return isset($a["image"]) && file_exists($a["image"]); }
foreach($groups as &$users){
$users = array_filter($users, "hasImage");
}

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories