How do i add more data into this array? - php

I am not very familiar with this type of array. How do i push another set of data in this type of array?
$array = array(
array(
'service_name' => $row['application_name'],
'html_id' => $row['html_id'],
'url' => $row['url']
)
);

as far as I understood-
$array[]= array(
'service_name' => $row['application_name'],
'html_id' => $row['html_id'],
'url' => $row['url']
);
will add another section, same as first

This adds another array to the outhermost array:
$array[] = array('key' => 'value', 'key2' => 'value2');

Always take the path of the PHP man my friend :) http://php.net/manual/en/function.array-push.php

it depends on which array you want to put data into :) - the first one is a classical array and the included one is an associative array

The answer really depends on what the application or API is expecting but to take a wild stab at it, something like -
<?php
$array = array (
array (
'service_name' => $row['application_name'],
'html_id' => $row['html_id'],
'url' => $row['url']
),
array (
'service_name' => 'app2',
'html_id' => 'htmlid2',
'url' => 'url2'
)
);

Related

PHP - How to dynamically add array to Object request

I am doing Jira REST API calls and I am wondering how I can dynamically add more than one component to the components field using REST API in PHP. I have the following code, works when I set it static, but not sure how to do it dynamically.
Example of static component set:
$data = array(
'fields' => array(
'project' => array(
'key' => $rowAnswers["Key"]
),
'summary' => $rowAnswers["Summary"],
'description' => $rowAnswers["Description"],
'issuetype' => array(
'name' => $rowAnswers["IssueType"]
),
'components' => array(
array(
"name" => "component1"
),
array(
"name" => "component2"
)
)
),
);
My array that I want to replace the static content with:
$components = explode(",", $rowAnswers["Components"]);
$arr = array();
foreach($components as $value){
$array = array("name"=>$value);
array_push($arr,$array);
}
Replacing
'components' => array(
array(
"name" => "component1"
),
array(
"name" => "component2"
)
)
with
'components' => [
$arr
]
doesn't work, I get:
"{"error":false,"error_msg":"","data":"{\"errorMessages\":[],\"errors\":{\"components\":\"expected Object\"}}"}"
I see on an api call to get a request it looks like this:
[components] => Array
(
[0] => stdClass Object
(
[name] => component1
)
[1] => stdClass Object
(
[name] => component2
)
)
But I am unsure how to transform an array into this type of object or request in PHP. Calling with PHP-cURL and json_encoding the data it sends.
Thanks in advance!
you need to decode your json as associative array by setting the second parameter to true
check out the json_decode
assoc
When TRUE, returned objects will be converted into associative arrays.
To fix this I had to do the following:
When creating the array from the DB:
$components = explode(",", $rowAnswers["Components"]);
$arr = array();
foreach($components as $value){
$array = json_decode(json_encode(array("name"=>$value)), FALSE);
array_push($arr,$array);
}
Then to set the component in the request:
'components' => $arr
Thanks

Storing the full location of an element in a multidimensional array for reuse

This question is based on my other question here about a suitable array processing algorithm.
In my case, I want to flatten a multidimensional array, but I need to store the full key to that element for reuse later.
For example :
array(
0 => array(
'label' => 'Item1',
'link' => 'http://google.com',
'children' => null
)
1 => array(
'label' => 'Item2',
'link' => 'http://google.com',
'children' => array( 3 => array(
'label' => 'SubmenuItem1',
'link' => 'http://www.yahoo.com',
'children' => null
)
)
)
2 => array(
'label' => 'Item3',
'link' => 'http://google.com',
'children' => null
)
)
Should be flattened into something like the following table
Key Link
===================================
[0] http://google.com
[1] http://google.com
[2] http://google.com
[1][3] http://yahoo.com
The problem is that I while I can easily store the location of an element in a multidimensional array, I am finding it to be quite hard to retrieve that element later. For example, if I store my key as $key = "[1][3]", I can not access it using $myarray[$key]. Is there anyway to do this?
Solution using recursion:
//Array parts should be an array containing the keys, for example, to address
//SubmenuItem1, I had 1.3 when the array was flattened. This was then exploded() to the array [1, 3]
$this->recurseIntoArray($myArray, $arrayParts);
private function recurseIntoArray(&$array, $arrayParts){
$current = $arrayParts[0];
$array[$current]['blah'] = 'blah'; //If you want to update everyone in the chain on the way down, do it here
array_shift($arrayParts);
if (!empty($arrayParts)){
$this->recurseIntoArray($array[$current]['children'], $arrayParts);
}else{
//If you want to update only the last one in the chain, do it here.
}
}

Insert new values in Sub-Arrays in PHP

I have array like this:
array(
'person0' => array( 'name'=>'name0','address'=>'address0' ),
'person1' => array( 'name'=>'name1','address'=>'address1' ),
'person2' => array( 'name'=>'name2','address'=>'address2' )
);
I want to change it like this. (just append a new value in each sub-array)
array(
'person0' => array( 'name'=>'name0','address'=>'address0','type'=>'type0' ),
'person1' => array( 'name'=>'name1','address'=>'address1','type'=>'type1' ),
'person2' => array( 'name'=>'name2','address'=>'address2','type'=>'type2' )
);
Is there any related function in php to perform this action? What is the shortest way to do this. Is it possible without loop?
Thanks
Browse the PHP manual when you wonder if a function exists to do something... it probably does.
http://www.php.net/manual/en/function.array-walk.php
http://php.net/manual/en/function.array-map.php
I'd just write the loop, but you can use those functions if you don't want to.

PHP / Mongo: how do you update nested data?

I've been playing around with Mongo for about a week now and I still can't work out how to modify nested arrays in Mongo with php.
So here is a sample document...
array (
'_id' => new MongoId("4cb30f560107ae9813000000"),
'email' => 'mo#maurice-campobasso.com',
'firstname' => 'Maurice',
'lastname' => 'Campobasso',
'password' => 'GOD',
'productions' =>
array (
0 =>
array (
'title' => 'a',
'date' => '1286811330.899',
),
1 =>
array (
'title' => 'b',
'date' => '1286811341.183',
),
2 =>
array (
'title' => 'c',
'date' => '1286811350.267',
),
3 =>
array (
'title' => 'd',
'date' => '1286811356.05',
),
),
)
What I wan't to do is delete an array inside the productions array, but I can't work out how. I've been playing with 'update('$pull' => ...etc)' but I haven't been able to make it work.
OK, there are a few ways to do this. In your case, I would do something like
mymongoobject.update( $unset : { "productions.2" : 1 } }
That's basically saying to unset the ".2" element of productions. Some docs here.
Now $pull should also work, but it's a little tougher because "productions" is actually an array of arrays (or objects with sub-objects). So you'd have to match arrays exactly:
mymongoobject.update( $pull : { "productions" : {'title':'d', 'date':'1286811356.05'} }
In the case above, the unset is probably the easiest option (though it will leave a "hole" in the array)
That is actually very easy, unlike traditional sql stuff you just modify the whole data and pass it back.
$cursor = $mongo->yourDB->yourCollection->findOne("_id",4cb30f560107ae9813000000);
//let's remove last item on productions
array_splice($cursor["productions"],2);
//and update the mongo document
echo $mongo->yourDB->yourCollection->update($cursor);
//it echoes 1 if successful
hope it helps.

Retrieve first key in multi-dimensional array using PHP

I would like to retrieve the first key from this multi-dimensional array.
Array
(
[User] => Array
(
[id] => 2
[firstname] => first
[lastname] => last
[phone] => 123-1456
[email] =>
[website] =>
[group_id] => 1
[company_id] => 1
)
)
This array is stored in $this->data.
Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.
Are there any other ways to retrieve this result?
Thanks
There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:
$keys=array_keys($this->data);
echo $keys[0]; //prints first key
foreach ($this->data as $key => $value)
{
echo $key;
break;
}
As you can see both are sloppy.
If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:
reset($this->data);
reset():
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?
Use this (PHP 5.5+):
echo reset(array_column($this->data, 'id'));
I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.
After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.
Here is a sample start array:
$myArray = array(
'referrer' => array(
'week' => array(
'201901' => array(
'Internal' => array(
'page' => array(
'number' => 201,
'visits' => 5
)
),
'External' => array(
'page' => array(
'number' => 121,
'visits' => 1
)
),
),
'201902' => array(
'Social' => array(
'page' => array(
'number' => 921,
'visits' => 100
)
),
'External' => array(
'page' => array(
'number' => 88,
'visits' => 4
)
),
)
)
)
);
As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:
function getFirstKeys($arr){
$keys = '';
reset($arr);
$key = key($arr);
$arr1 = $arr[$key];
if (is_array($arr1)){
$keys .= $key . '|'. getFirstKeys($arr1);
} else {
$keys = $key;
}
return $keys;
}
When the function is called using the code:
$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';
the output is:
Get First Keys
The keys are: referrer|week|201901|Internal|page|number
I hope this saves someone a bit of time should they encounter a similar problem.

Categories