Pushing values into multidimensional array [duplicate] - php

This question already has answers here:
PHP add elements to multidimensional array with array_push
(4 answers)
Closed 2 years ago.
I'm already getting below array results as follows. All I wanted is to add more entries in it.
How do I do that?
Array
(
[result] => Array
(
[0] => Array
(
[number] => AAA1222
[short_description] => User unable to print
[state] => Closed
)
[1] => Array
(
[number] => AAA1223
[short_description] => Share drive not accessible
[state] => Closed
)
[2] => Array
(
[number] => AAA1224
[short_description] => Network is down
[state] => Closed
)
)
)
If I wanted to add more entries to the array like
[number] => AAA1225
[short_description] => Cable replacement on workstation 12
[state] => Closed
How do I accomplish that.
Thanks!!

You can try with array_push() function too.
Your existence array:
$myArr['result'] = [........]
New array values
$data['number'] = 'AAA1224';
$data['short_description'] = 'Network is down';
$data['state'] = 'Closed';
Push new array into existance array:
array_push($myArr['result'],$data);

Considering you are storing above array in a variable named as $arr.
$arr = [ ... ]; // contains your existing data.
// To add new data
$arrNewData = [
'number' => 'AAA1225',
'short_description' => 'Cable replacement on workstation 12',
'state' => 'Closed'
];
// Push data to existing array.
$arr['result'][] = $arrNewData;

You can add another array data to your existing array
Keep your existing data into a variable $data.
$data = [ ... ]; // here you have result index and array data
Then add new result item as an array.
$data['result'][] = [
'number' => 'AAA1225',
'short_description' => 'Cable replacement on workstation 12',
'state' => 'Closed'
];

Related

How do I iterate list of dictionary in PHP? [duplicate]

This question already has answers here:
Loop through a two-dimensional array
(6 answers)
Closed 2 years ago.
How do I iterate list of dictionary returned from curl response in PHP?
Here is structure of a returned response:
Array (
[0] => Array (
[status] => open
[serviceSpecification] => https://testdomain.com
[expirationDate] =>
[name] => abcd.com
[service] => servicekey
[domainName] => domainname
[productInstanceUrl] => https://anotherinstanceurl.com
[createDate] => 2019-04-15
[serviceSpecificationTextKey] => test.core.key
[billingCycle] => 1
)
[1] => Array (
[status] => open
[serviceSpecification] => https://test.net
[expirationDate] =>
[name] => testname
[service] => https://service.com
[domainName] => test
[productInstanceUrl] => https://instanceurl.com
[createDate] => 2019-04-15
[serviceSpecificationTextKey] => core.test.key
[billingCycle] => 1
)
)
I tried doing following but not working:
foreach ($aboveVariable as $record) {
echo $record['domainName'];
}
Note: I believe its more of a how to iterate through list of list in PHP?
To just show the domainName for each then the code you show works. But based on this I believe its more of a how to iterate through list of list in PHP? I would say you just want to loop the main array and then the sub-arrays:
foreach($aboveVariable as $record) {
foreach($record as $name => $value) {
echo "$name = $value<br>\n";
}
echo "<br>\n";
}
Will show something like:
status = open
serviceSpecification = https://testdomain.com
etc...
status = open
serviceSpecification = https://test.net
etc...

How do you combine data from multiple loops into the same numeric key in a multidimensional array? [duplicate]

This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 2 years ago.
I would like to collate data from multiple different data sources into one numeric array using foreach loops, however I am having some trouble building my array in the expected format. I would like to keep the key numeric.
For example, if I had two data sources: $fruit_data and $flavor_data and my code was:
foreach($fruit_data as $fruit){
$fruits[]['name'] = $fruit['name'];
}
foreach($flavor_data as $flavor){
$fruits[]['flavor'] = $flavor['taste'];
}
The data is added to the array with separate numeric keys, like this:
Array
(
[0] => Array
(
[name] => Example Name 1
)
[1] => Array
(
[flavor] => Example Flavor 1
)
[2] => Array
(
[name] => Example Name 2
)
[3] => Array
(
[flavor] => Example Flavor 2
)
)
However, my desired output is to display the data under the same numeric key, like this:
Array
(
[0] => Array
(
[name] => Example Name 1
[flavor] => Example Flavor 1
)
[1] => Array
(
[name] => Example Name 2
[flavor] => Example Flavor 2
)
)
Could somebody please explain where I am going wrong, and if possible, link me to a resource that explains how to overcome this issue? It may be that I have a fundamental misunderstanding of multidimensional arrays, but I cannot seem to find any references to this issue.
Any help is much appreciated.
foreach($fruit_data as $index => $fruit){
$fruits[] = [
'name' => $fruit['name'],
'flavor' => $flavor_data[$index]['taste']
];
}
Same as
foreach($fruit_data as $index => $fruit){
$fruits[] = [
'name' => $fruit_data[$index]['taste'],
'flavor' => $flavor_data[$index]['taste']
];
}

Move or shift php array keys [duplicate]

This question already has answers here:
Get first value of an array [duplicate]
(5 answers)
PHP: How to access the first element of an array returned by a static function [duplicate]
(2 answers)
Closed 2 years ago.
Not quite sure how to word this correctly, but I am looking for some help to to move/shift array keys so that the top level array doesn't contain another array with only one item. Basically from this:
[0] => Array
(
[0] => Array
(
[_id] => 3
[title] => Award winning wedding venue
[subtitle] => Creating a website to reflect the prestige of the brand
)
)
[1] => Array
(
[0] => Array
(
[_id] => 5
[title] => Bringing storytelling to life
[subtitle] => Bringing storytelling to life
)
)
to be like this:
[0] => Array
(
[_id] => 3
[title] => Award winning wedding venue
[subtitle] => Creating a website to reflect the prestige of the brand
)
[1] => Array
(
[_id] => 5
[title] => Bringing storytelling to life
[subtitle] => Bringing storytelling to life
)
Almost just shifting the array key up one.
The original array is created using the following:
// Start with manual relation otherwise default to next/prev
foreach ($item['related'] as $id) {
$related[] = perch_collection('Projects', [
'filter' => [
[
'filter' => '_id',
'match' => 'eq',
'value' => $id,
],
// Item is enabled
[
'filter' => 'status',
'match' => 'eq',
'value' => 'enabled',
],
],
'skip-template' => true,
], true);
}
It would be best if you modify the creation of your array instead of changing it afterwards.
// Start with manual relation otherwise default to next/prev
foreach ($item['related'] as $id) {
$related[] = perch_collection('Projects', [
'filter' => [
[
'filter' => '_id',
'match' => 'eq',
'value' => $id,
],
// Item is enabled
[
'filter' => 'status',
'match' => 'eq',
'value' => 'enabled',
],
],
'skip-template' => true,
], true)[0];
}
Note the [0] at the end of the perch_collection() function call. This is essentially the same as the second part of my answer, it just occurs earlier.
With that said, if you still want to change it after the original array is made, you could just use a simple foreach loop with a reference to the original array.
foreach($array as &$arr) {
$arr = $arr[0];
}
Using & in front of $arr is a reference. This means the loop will alter the original array, so it prevents the overhead of a temporary array.
mickmackusa let me know about another solution using array_column(), which avoids the loop completely.
$array = array_column($array, 0);
The best way to fix this problem would be at the source. This looks like a Dataset received from a database, so instead of trying to manipulate the array after you received it, you could also try to generate it in the correct format. Most DALs have methods to manipulate the return type of the resultset.
However, if that is not possible and you always only have a single element nested, this loop should do the trick.
for($i = 0; $i <= count($array); $i++) {
$shifted[$i] = $array[$i][0];
}

How to push an object to laravel db? [duplicate]

This question already has answers here:
In PHP how can I access a ":private" array in an object?
(3 answers)
Convert a PHP object to an associative array
(33 answers)
Closed 5 years ago.
I'm working with Laravel, and I have an Object that I must push to my DB, the thing is, this is an Object, and I need it to be an array to push it in, Ill explain here:
so, this is how Im pushing in the array to my DB:
$subset = collect($MYARRAY);
$arr = $subset->map (function ($item) {
$now = Carbon::now('utc')->toDateTimeString();
return array(
'order_id' => $item['data']['AmazonOrderId'],
'buyer_name' => $item['data']['BuyerName'],
'buyer_email' => $item['data']['BuyerEmail'],
'store_name' => $item['storeName'],
'ship_service_level' => $item['data']['ShipServiceLevel'],
'order_status' => $item['data']['OrderStatus'],
'fulfillment_channel' => $item['data']['FulfillmentChannel'],
'purchase_date' => $item['data']['PurchaseDate'],
'last_ship_date' => $item['data']['LatestShipDate'],
'created_at'=> $now,
'updated_at'=> $now
);
})->all();
$order->insert($arr);
This code is working great, If I have this $MYARRAY (I created the array manually):
$MYARRAY = array (
0 =>
array(
'data' =>
array (
[AmazonOrderId] => 111
[SellerOrderId] => 222
[PurchaseDate] => 2013-05-31T15:20:59Z
[LastUpdateDate] => 2013-06-01T18:00:41Z
...
))
1 =>
array(
'data' =>
array (
...
)
);
But, it fails in this object (this is var_export of the object):
Array
(
[0] => Sonnenglas\AmazonMws\AmazonOrder Object
(
[data:Sonnenglas\AmazonMws\AmazonOrder:private] => Array
(
[AmazonOrderId] => 111
[SellerOrderId] => 222
[PurchaseDate] => 2013-05-31T15:20:59Z
[LastUpdateDate] => 2013-06-01T18:00:41Z
...
)
)
[1] => Sonnenglas\AmazonMws\AmazonOrder Object
(
[data:Sonnenglas\AmazonMws\AmazonOrder:private] => Array
(
[AmazonOrderId] => 2345
[SellerOrderId] => 2345
[PurchaseDate] => 2013-06-01T02:11:24Z
...
))
Now, this is what I have tried, I tried to convert it to array like that:
$array = json_decode(json_encode($object), true);
but then I had an empty arrays (the conversion to json and back deleted it all because of the object type I guess).
I have tried this one as well:
$MYARRAY = array_map(function($object){
return (array) $object;
}, $data);
With no success, (I have tried also to cast it to array with foreach) so, can you please help, how can I convert this object back to array, or, how can I map the object to push it in the DB?
Thank you!

PHP Get Values from POST Array [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 6 years ago.
I'm processing a form that submits to my PHP page. The request data looks like this:
Array
(
[submission_id] => 363112875894117228
[name] => Array
(
[0] => Tom
[1] => Jones
)
[address] => Array
(
[0] => 21 Jump St
[1] =>
[2] => Sydney
[3] => NSW
[4] => 2000
[5] => Australia
)
[cellularnumber] => Array
(
[0] => (041) 234-5678
)
)
I'm trying to set a variable that contains the value of the first name, last name etc. For example I would like to set a variable:
$firstName
that is equal to Tom.
I'm familiar with using this syntax:
$firstName = $_POST['name']
but not sure how to handle the array in this case?
use array index for name like
$fname = $_POST['name'][0];
$lname = $_POST['name'][1];
and use implode statement for the address like
implode(" ",$_POST['address']) (it will convert your address array to string)
Have you tried like this , I hope this should work for you.
$firstName = $_POST['name'][0];
$lastName = $_POST['name'][1];
Its a multidimensional array. In your case the array element name have one more sub array. You can access it as follows,
$firstName = $_POST['name'][0];
$lastName = $_POST['name'][1];
You can convert the whole array to JSON to POST using json_encode, then use json_decode to fetch all data at backend.
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php
$result = json_encode(Array
(
'submission_id' => 363112875894117228,
'name' => Array
(
0 => 'Tom',
1 => 'Jones',
),
'address' => Array
(
0 => '21 Jump St',
1 => '',
2 => 'Sydney',
3 => 'NSW',
4 => '2000',
5 => 'Australia',
),
'cellularnumber' => Array
(
0 => '(041) 234-5678',
),
))
End up to {"submission_id":363112875894117228,"name":["Tom","Jones"],"address":["21 Jump St","","Sydney","NSW","2000","Australia"],"cellularnumber":["(041) 234-5678"]}

Categories