This one should be straight forward, but I am having issues as I have not worked with arrays that much.
So I am try to insert data into a 3 dimensional array, this is the structure of my 3 dimensional array:
Array
(
[data] => Array
(
[0] => Array
(
[name] => name
[by] => by
[imgUrl] => imgUrl
[linkUrl] => linkUrl
[date] => date
)
[1] => Array
(
[name] => name
[by] => by
[imgUrl] => imgUrl
[linkUrl] => linkUrl
[date] => date
)
)
)
I am trying to push the existing array downwards, the existing [0] becomes [1], ect. While the new [0] will be the posted data from a form.
I have tried array_push, array_splice, array_merge, but all to no avail.
if I understood you correctly...
here's a fiddle.
$multi = array(
"data" =>array(
array(
'something1' => 'something else',
'something0' => 'something else',
'something345' => 'something else'
),
array(
'something1' => 'something else',
'something0' => 'something else',
'something345' => 'something else'
),
)
);
$new = array(
'something1' => 'something else',
'something0' => 'something else',
'something345' => 'something else'
);
array_push($multi['data'], $new);
print_r($multi);
You are looking for the array_unshift function:
array_unshift($arr["data"], $new);
Test script:
$arr = Array(
"data" => Array(
Array(
"name" => "name",
"by" => "by",
"imgUrl" => "imgUrl",
"linkUrl" => "linkUrl",
"date" => "date"
)
,Array(
"name" => "lastname",
"by" => "by",
"imgUrl" => "imgUrl",
"linkUrl" => "linkUrl",
"date" => "date"
)
)
);
$new = Array(
"name" => "newname",
"by" => "newby",
"imgUrl" => "newimgUrl",
"linkUrl" => "newlinkUrl",
"date" => "newdate"
);
array_unshift($arr["data"], $new);
print_r ($arr);
Output shows that new element pushes the other elements down:
array(1) {
["data"]=> array(3) {
[0]=> array(5) {
["name"]=> string(7) "newname"
["by"]=> string(5) "newby"
["imgUrl"]=> string(9) "newimgUrl"
["linkUrl"]=> string(10) "newlinkUrl"
["date"]=> string(7) "newdate"
}
[1]=> array(5) {
["name"]=> string(4) "name"
["by"]=> string(2) "by"
["imgUrl"]=> string(6) "imgUrl"
["linkUrl"]=> string(7) "linkUrl"
["date"]=> string(4) "date"
}
[2]=> array(5) {
["name"]=> string(9) "firstname"
["by"]=> string(2) "by"
["imgUrl"]=> string(6) "imgUrl"
["linkUrl"]=> string(7) "linkUrl"
["date"]=> string(4) "date"
}
}
}
Related
This question already has answers here:
How to push both value and key into PHP array
(21 answers)
Closed 10 months ago.
Please note that this is not a duplicate - but an extension of these questions below)
PHP array_push one array into another
array_push into a multi-dimensional array
I am trying to array_push into a multidimensional array but want to keep the array key of the second array.
Example:
<?php
$samplearray = array(
array('name' => "Joe Bloggs", 'age' => "30", 'sex' => "Male", 'title' => "Mr" ),
array('name' => "Jane Bloggs", 'age' => "30", 'sex' => "Female", 'title' => "Mrs" ),
array('name' => "Little Bloggs", 'age' => "10", 'sex' => "Male", 'title' => "Master" ),
);
array_push ($samplearray[0],"Inserted Value");
print_r($samplearray);
?>
The output for this is:
array(3) {
[0]=>
array(5) {
["name"]=>
string(10) "Joe Bloggs"
["age"]=>
string(2) "30"
["sex"]=>
string(4) "Male"
["title"]=>
string(2) "Mr"
[0]=>
string(14) "Inserted Value" <-- INSERTED VALUE
}
[1]=>
array(4) {
["name"]=>
string(11) "Jane Bloggs"
["age"]=>
string(2) "30"
["sex"]=>
string(6) "Female"
["title"]=>
string(3) "Mrs"
}
[2]=>
array(4) {
["name"]=>
string(13) "Little Bloggs"
["age"]=>
string(2) "10"
["sex"]=>
string(4) "Male"
["title"]=>
string(6) "Master"
}
}
I want to insert a key along with the value but when I try that - it fails. Can you please advice
array_push ($samplearray[0]['insertedvalue'],"Inserted Value");
returns a NULL value for the inserted key on local server but fails on PHPfiddle.
is this what you are looking for?
$samplearray = array(
array('name' => "Joe Bloggs", 'age' => "30", 'sex' => "Male", 'title' => "Mr" ),
array('name' => "Jane Bloggs", 'age' => "30", 'sex' => "Female", 'title' => "Mrs" ),
array('name' => "Little Bloggs", 'age' => "10", 'sex' => "Male", 'title' => "Master" ),
);
$samplearray[0]['othername'] = 'lalala';
echo '<pre>';
print_r($samplearray);
and this should print:
Array
(
[0] => Array
(
[name] => Joe Bloggs
[age] => 30
[sex] => Male
[title] => Mr
[othername] => lalala
)
[1] => Array
(
[name] => Jane Bloggs
[age] => 30
[sex] => Female
[title] => Mrs
)
[2] => Array
(
[name] => Little Bloggs
[age] => 10
[sex] => Male
[title] => Master
)
)
This must be what you need.
$samplearray[0]['insertedvalue'] = "Inserted Value";
I have arrays in one submission, please see below details:
array(5) {
["ambition_id"]=>
array(2) {
[55]=> string(2) "55"
[60]=> string(2) "60"
}
["target"]=>
array(1) {
[0]=> string(8) "target 1"
[1]=> string(8) "target 2"
}
["strides"]=>
array(1) {
[0]=> string(1) "1"
[1]=> string(1) "1"
}
["date"]=>
array(1) {
[0]=> string(10) "2017-02-08"
[1]=> string(10) "2017-03-08"
}
["frequency"]=>
array(1) {
[0]=> string(1) "1"
[1]=> string(1) "2"
}
}
Actually, I have two tables in mysql, 'ambition' and 'target'. Ambition is a group of targets ('ambition_id' is foreign key in 'target' table). That array will be stored in 'target' table. That's why there is an 'ambition_id'
I've tried many times but failed (using foreach), now I need someone who can give me a help.
By brute force, It's easy! I solved it already but I need "more advanced" array manipulation.
How can I come up into this?
array(2) {
[0] => array('ambition_id' => 55,
'target' => 'target 1',
'strides' => 1,
'date' => '2017-02-08',
'frequency' => 1
),
[1] => array('ambition_id' => 60,
'target' => 'target 2',
'strides' => 2,
'date' => '2017-03-08',
'frequency' => 2)
}
Please do help, many thanks!
You have to pivot your data:
$data = array (
"ambition_id" =>
array (
55 => "55",
60 => "60"
),
"target" =>
array (
0 => "target 1",
1 => "target 2"
),
"strides" =>
array (
0 => "1",
1 => "1"
),
"date" =>
array (
0 => "2017-02-08",
1 => "2017-03-08"
),
"frequency" =>
array (
0 => "1",
1 => "2"
)
);
// pivot data
$pivot = array();
foreach ($data as $datum => $values) {
$value_index = 0;
foreach ($values as $value) {
$pivot[$value_index][$datum] = $value;
$value_index++;
}
}
print_r($pivot);
This assumes you only have two levels of data and that the data is well behaved.
Not the best answer, but it solves your problem
<?php
$array = [
"ambition_id" =>
[
55 => "55",
60 => "60"
],
"target" =>
[
0 => "target 1",
1 => "target 2"
],
"strides" =>
[
0 => "1",
1 => "1"
],
"date" =>
[
0 => "2017-02-08",
1 => "2017-03-08"
],
"frequency" =>
[
0 => "1",
1 => "2"
],
];
$result = array();
foreach ($array as $k => $v) {
foreach ($v as $kk => $vv) {
if ($k == "ambition_id") {
$result[] = array($k => $vv);
} else {
$result[$kk][$k] = $vv;
}
}
}
Here is the test https://3v4l.org/UdHH8
Just use loop the array and user array_values to re-index the loop the inner array and store it into new array like below .
<?php
$new_array =array();
foreach($array as $key1=>$row1 )
{
$ss =array_values($row1);
foreach($ss as $key2=>$row2)
{
$new_array[$key2][$key1]=$row2;
}
}
echo "<pre>";
print_r($new_array);
?>
Output :
Array
(
[0] => Array
(
[ambition_id] => 55
[target] => target 1
[strides] => 1
[date] => 2017-02-08
[frequency] => 1
)
[1] => Array
(
[ambition_id] => 60
[target] => target 2
[strides] => 1
[date] => 2017-03-08
[frequency] => 2
)
)
How do I merge these two arrays:
Array
(
[uczrrtawpxfjanycwwlqygoq] => Array
(
[user_id] => 53
[value] => Boris
[key] => uczrrtawpxfjanycwwlqygoq
)
[dreamhack] => Array
(
[user_id] => 263
[value] => More
[key] => dreamhack
)
)
And my second array which needs to be added to the keys of the first
Array
(
[dreamhack] => Array
(
[viewers] => 32229
[channel] => Array
(
[broadcaster_language] => en
[display_name] => Dreamhack
[_id] => 22859340
[created_at] => 2011-06-09T06:11:52Z
[updated_at] => 2016-08-14T18:34:36Z
[delay] =>
[banner] =>
[background] =>
[partner] => 1
[views] => 36258931
[followers] => 79892
[_links] => Array
(
[self] =>
[teams] =>
)
)
)
)
Doing a simple array merge gives the original array and not a combined one. So for dreamhack I would require one aeeay with all the tags combined [user_id], [value], [key], [viewers], [channel] and subarray.
as asked in the comment .. is this what you want ?
<pre>
<?php
$array1 = [
'uczrrtawpxfjanycwwlqygoq' => [
'user_id' => 53,
'value' => 'Boris',
'key' => 'uczrrtawpxfjanycwwlqygoq'
],
'dreamhack' => [
'user_id' => 263,
'value' => 'More',
'key' => 'dreamhack'
]
];
$array2 = [
'dreamhack' => [
'viewers' => 32229,
'channel' => [
'broadcaster_language' => 'en',
'display_name' => 'Dreamhack',
'_id' => 22859340,
'created_at' => '2011-06-09T06:11:52Z',
'updated_at' => '2016-08-14T18:34:36Z',
'delay' => '',
'banner' => '',
'background' => '',
'partner' => 1,
'views' => 36258931,
'followers' => 79892,
'_links' => [
'self' => '',
'teams' => ''
]
]
]
];
$result = array_merge_recursive ($array1, $array2);
var_dump($result);
?>
</pre>
result looks like:
array(2) {
["uczrrtawpxfjanycwwlqygoq"]=>
array(3) {
["user_id"]=>
int(53)
["value"]=>
string(5) "Boris"
["key"]=>
string(24) "uczrrtawpxfjanycwwlqygoq"
}
["dreamhack"]=>
array(5) {
["user_id"]=>
int(263)
["value"]=>
string(4) "More"
["key"]=>
string(9) "dreamhack"
["viewers"]=>
int(32229)
["channel"]=>
array(12) {
["broadcaster_language"]=>
string(2) "en"
["display_name"]=>
string(9) "Dreamhack"
["_id"]=>
int(22859340)
["created_at"]=>
string(20) "2011-06-09T06:11:52Z"
["updated_at"]=>
string(20) "2016-08-14T18:34:36Z"
["delay"]=>
string(0) ""
["banner"]=>
string(0) ""
["background"]=>
string(0) ""
["partner"]=>
int(1)
["views"]=>
int(36258931)
["followers"]=>
int(79892)
["_links"]=>
array(2) {
["self"]=>
string(0) ""
["teams"]=>
string(0) ""
}
}
}
}
Use array_merge_recursive, which is specifically designed to do this sort of thing. To quote the docs:
array_merge_recursive() merges the elements of one or more arrays
together so that the values of one are appended to the end of the
previous one. It returns the resulting array.
If the input arrays have the same string keys, then the values for
these keys are merged together into an array, and this is done
recursively, so that if one of the values is an array itself, the
function will merge it with a corresponding entry in another array
too. If, however, the arrays have the same numeric key, the later
value will not overwrite the original value, but will be appended.
I have an associative array , i would like to add some more key and values
Array
(
[0] => Array
(
[NUMBER] => 67
[TYPE] => Other
[DATE] => 3/31/2011
)
[1] => Array
(
[NUMBER] => 87
[TYPE] => something
[DATE] => 3/28/2011
)
[2] => Array
(
[NUMBER] => 67
[TYPE] => Other
[DATE] => 3/2/2011
)
)
In Above array i want to add another key named STATUS and value before DATE
so that finally iget
Array
(
[0] => Array
(
[NUMBER] => 67
[TYPE] => Other
[STATUS] => waiting
[DATE] => 3/31/2011
)
}
canPlease give me proper direction
$arr = Array(
0 => Array('NUMBER' => 67, 'TYPE' => Other, 'DATE' => '3/32/2011'),
1 => Array('NUMBER' => 87, 'TYPE' => something, 'DATE' => '3/28/2011'),
2 => Array('NUMBER' => 67, 'TYPE' => Other, 'DATE' => '3/2/2011')
);
foreach($arr as $key => $value) {
$arr[$key] = array_slice($value, 0, 2) +
array('Status' => 'waiting') +
array_slice($value, -1);
}
var_dump($arr);
gives the following array:
array(3) {
[0]=>
array(4) {
["NUMBER"]=>
int(67)
["TYPE"]=>
string(5) "Other"
["Status"]=>
string(7) "waiting"
["DATE"]=>
string(9) "3/32/2011"
}
[1]=>
array(4) {
["NUMBER"]=>
int(87)
["TYPE"]=>
string(9) "something"
["Status"]=>
string(7) "waiting"
["DATE"]=>
string(9) "3/28/2011"
}
[2]=>
array(4) {
["NUMBER"]=>
int(67)
["TYPE"]=>
string(5) "Other"
["Status"]=>
string(7) "waiting"
["DATE"]=>
string(8) "3/2/2011"
}
}
I have an array of items that all have start and end dates associated with them. I'd like to group them according to closest start and end dates without any of them overlapping, but I'm having difficulty conjuring what the logic for this should look like.
Let's say I start with this:
$query = array(
[0] =>
array(
[0] =>
array(
['name'] =>'A'
['start'] =>'1/1/2011'
['end'] =>'1/31/2011'
)
[1] =>
array(
['name'] =>'B'
['start'] =>'1/15/2011'
['end'] =>'1/31/2011'
)
[2] =>
array(
['name'] =>'C'
['start'] =>'2/1/2011'
['end'] =>'2/28/2011'
)
[3] =>
array(
['name'] =>'D'
['start'] =>'2/2/2011'
['end'] =>'2/28/2011'
)
[4] =>
array(
['name'] =>'E'
['start'] =>'1/31/2011'
['end'] =>'3/1/2011'
)
[5] =>
array(
['name'] =>'F'
['start'] =>'3/3/2011'
['end'] =>'3/31/2011'
)
)
)
And I want to finish with this:
$result = array(
[0] =>
array(
[0] =>
array(
['name'] =>'A'
['start'] =>'1/1/2011'
['end'] =>'1/31/2011'
)
[1] =>
array(
['name'] =>'C'
['start'] =>'2/1/2011'
['end'] =>'2/28/2011'
)
[2] =>
array(
['name'] =>'F'
['start'] =>'3/3/2011'
['end'] =>'3/31/2011'
)
)
[1]=>
array(
[0] =>
array(
['name'] =>'B'
['start'] =>'1/15/2011'
['end'] =>'1/31/2011'
)
[1] =>
array(
['name'] =>'D'
['start'] =>'2/2/2011'
['end'] =>'2/28/2011'
)
)
[2]=>
array(
[0] =>
array(
['name'] =>'E'
['start'] =>'1/31/2011'
['end'] =>'3/1/2011'
)
)
)
edit: by request, the var_export for the input and output listed above:
$query = array ( 0 => array ( 'name' => 'A', 'start' => '1/1/2011', 'end' => '1/31/2011', ), 1 => array ( 'name' => 'B', 'start' => '1/15/2011', 'end' => '1/31/2011', ), 2 => array ( 'name' => 'C', 'start' => '2/1/2011', 'end' => '2/28/2011', ), 3 => array ( 'name' => 'D', 'start' => '2/2/2011', 'end' => '2/28/2011', ), 4 => array ( 'name' => 'E', 'start' => '1/31/2011', 'end' => '3/1/2011', ), 5 => array ( 'name' => 'F', 'start' => '3/3/2011', 'end' => '3/31/2011', ), )
$result = array ( 0 => array ( 0 => array ( 'name' => 'A', 'start' => '1/1/2011', 'end' => '1/31/2011', ), 1 => array ( 'name' => 'C', 'start' => '2/1/2011', 'end' => '2/28/2011', ), 2 => array ( 'name' => 'F', 'start' => '3/3/2011', 'end' => '3/31/2011', ), ), 1 => array ( 0 => array ( 'name' => 'B', 'start' => '1/15/2011', 'end' => '1/31/2011', ), 1 => array ( 'name' => 'D', 'start' => '2/2/2011', 'end' => '2/28/2011', ), ), 2 => array ( 0 => array ( 'name' => 'E', 'start' => '1/31/2011', 'end' => '3/1/2011', ), ), )
The best I have so far is to loop through the items in $query, and for each one, compare the start date to the end date of the last item in each of the arrays. Even as I'm typing this out I'm realizing that that would assume we're starting with a $query array that's already in some sort of chronological order (it's random.)
We are trying to put a GANTT timeline together with this data, using as few rows as possible to help visualize what our open schedule looks like. It has me stumped. Anyone who can point to the most efficient method of organizing these objects, it'd be greatly appreciated.
I have what I believe to be the start of the answer here.
I'm looping through the $query and using unset() on each object as it's added to arrays within $result.
Hopefully what's written here is as efficient as possible:
function cmp($a, $b){
return strcmp($a['start'], $b['start']);
}
$query = array(array('name' =>'A','start' =>'1/1/2011','end' =>'1/31/2011'),array('name' =>'B','start' =>'1/15/2011','end' =>'1/31/2011'),array('name' =>'C','start' =>'2/1/2011','end' =>'2/28/2011'),array('name' =>'D','start' =>'2/2/2011','end' =>'2/28/2011'),array('name' =>'E','start' =>'1/31/2011','end' =>'3/1/2011'), array('name' =>'F','start' =>'3/3/2011','end' =>'3/31/2011'));
usort($query, "cmp"); // organize by start date
$result = array();
$c = count($query);
for($i = 1; $i <= $c; $i++) {
if (empty($result)) {
$result[0][0] = $query[0];
unset($query[0]);
$query = array_values($query);
} else {
$lastkey_group = array_pop(array_keys($result));
$lastkey_object = array_pop(array_keys($result[$lastkey_group]));
// get the last object's end date
$last_end_date = strtotime($result[$lastkey_group][$lastkey_object]['end']);
$match_days = 1000;
$match_key = 1000;
foreach($query as $key => $q) {
$this_start_date = strtotime($q['start']);
$diff = round(($this_start_date - $last_end_date)/86400);
// compare to start date in each $q
if($diff < $match_days && $diff >= 0) {
// if the distance is greater than 0 but less than $diff,
// replace match with distance and row key
$match_days = $diff;
$match_key = $key;
}
}
if($match_key == 1000) {
$result[$lastkey_group + 1][0] = $query[0]; // no good matches. write to a new group
unset($query[0]);
$query = array_values($query);
} else {
$result[$lastkey_group][$lastkey_object + 1] = $query[$match_key];
// match. write to this group
unset($query[$match_key]);
$query = array_values($query);
}
}
}
var_dump($result);
And here's the output of this:
array(3) { [0]=> array(3) { [0]=> array(3) { ["name"]=> string(1) "A" ["start"]=> string(8) "1/1/2011" ["end"]=> string(9) "1/31/2011" } [1]=> array(3) { ["name"]=> string(1) "E" ["start"]=> string(9) "1/31/2011" ["end"]=> string(8) "3/1/2011" } [2]=> array(3) { ["name"]=> string(1) "F" ["start"]=> string(8) "3/3/2011" ["end"]=> string(9) "3/31/2011" } } [1]=> array(2) { [0]=> array(3) { ["name"]=> string(1) "B" ["start"]=> string(9) "1/15/2011" ["end"]=> string(9) "1/31/2011" } [1]=> array(3) { ["name"]=> string(1) "C" ["start"]=> string(8) "2/1/2011" ["end"]=> string(9) "2/28/2011" } } [2]=> array(1) { [0]=> array(3) { ["name"]=> string(1) "D" ["start"]=> string(8) "2/2/2011" ["end"]=> string(9) "2/28/2011" } } }