build dynamic associative multi-dimensional array - php

I have seen a lot of questions regarding multi-dimensional arrays, and how to build them, and whilst trying some of the answers I still get an error. So I am thinking what I am trying to do is not really possible, and perhaps I should use JSON instead?
I have data from a source which is returned as a JSON object. It has lots data in it, of which i only need a small amount. Now I need it sorted into dates:
$temp_array = array();
foreach ($data as $booking_id => $booking) {
$setdate = '';
$b = $this->getBooking($booking_id);
foreach ($b as $k => $v) {
$setdate = date('d-m-Y', $booking['start_date']);
if(!in_array($setdate, $temp_array)) {
$temp_array = array('date' => $setdate);
}
$temp_array['date'][] = array($k => $v);
}
}
I need the date to be the first node of the array, and the data to be in the second node. When a new date is found in the iteration, it creates another new node:
[0] => 1/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
[1] => 7/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
[2] => 14/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
[3] => 21/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
I seem unable to get anywhere with it as the errors I get refer to [] operator not supported for strings or Warning: Attempt to modify property of non-object in depending on what other examples on here I have found.
I think the question here, is that the data is not in any order, so it may populate node [0], and then [3], and then back to [0], and so on.
Any ideas what on earth I am doing wrong ?
Thanks
Addy
Update
Using this code, which is the middle foreach:
$b = $this->getBooking($booking_id);
foreach ($b as $k => $v) {
$setdate = date('d-m-Y', strtotime($booking['date_desc']));
if(!in_array($setdate, $temp_dates)) {
array_push($temp_dates, $setdate);
$temp_array[]['date'] = $setdate;
}
}
Gives me this result:
Array ( [0] => Array ( [date] => 22-10-2016 )
[1] => Array ( [date] => 01-10-2016 )
[2] => Array ( [date] => 08-10-2016 )
[3] => Array ( [date] => 15-10-2016 )
)
Which is correct. So now, I need to add, each time a date arrives which $tem_array has a heading for, add another array:
Array ( [0] => Array ( [date] => 22-10-2016 ) => [0] => $data
[1] => $data
[2] => $data
[1] => Array ( [date] => 01-10-2016 ) => [0] => $data
[1] => $data
[2] => $data
[2] => Array ( [date] => 08-10-2016 ) => [0] => $data
[3] => Array ( [date] => 15-10-2016 ) => [0] => $data
[1] => $data
)
Hope this explains it a little better. I have the first bit correct, but when a date is already in there, I need to move up a node.

I think I was over complicating it. This is the final code which did want I wanted.
function sortcf($data) {
$temp_array = array();
$temp_dates = array();
foreach ($data as $booking_id => $booking) {
$b = $this->getBooking($booking_id);
$setdate = date('d-m-Y', strtotime($booking['date_desc']));
$temp_array[$setdate][] = ($b);
}
$this->wcg_am_data = $temp_array;
}

Related

php foreach multidimensional array getting information

I'm having some troubles getting information from an array. I'm in need to get all information per key basis but I can't get it.
I have this array:
Array(
[en] => Array(
[a] => Array(
[0] => [C][C]
[1] => [L][L][C]
) [b] => Array(
[0] => Tackle
[1] => RazorLeaf
) [c] => Array(
[0] =>
[1] =>
) [d] => Array(
[0] => 20
[1] => 50
)
) [pt] => Array(
[a] => Array(
[0] => [C][C]
) [b] => Array(
[0] => Pontapé
) [c] => Array(
[0] =>
) [d] => Array(
[0] => 20
)
)
)
In a foreach (or multiple), I'm in need to get [en][a][0], [en][b][0], [en][c][0] and [en][d][0] to insert data into database.
In the next loop is supposed to get [en][a][1], [en][b][1], [en][c][1] and [en][d][1] .
Last but not least, after change from [en] to [pt] it should get [pt][a][0], [pt][b][0], [pt][c][0] and [pt][d][0]
My approach:
foreach($result as $language => $index){
foreach($index as $attinfo => $index2){
//echo "$language <br/> $attinfo <br/>";
foreach($index2 as $valorfinal => $index3){
echo $index[$attinfo][$valorfinal][$index3]."<br/>";
}
}
}
My approach seems not to work as expected. Could someone guide me please?
I would like to save in vars each key to then save them in database in each foreach loop. Thanks.
I've re-organised the loops and corrected the indexes used in the final data access (you are using [$index3] as an index when it's a value)...
foreach($result as $index){
foreach($index['a'] as $key => $value){
$data = [];
foreach ( $index as $key1 => $value1) {
$data[] = $index[$key1][$key];
}
print_r($data);
}
}
this outputs...
Array
(
[0] => [C][C]
[1] => Tackle
[2] =>
[3] => 20
)
Array
(
[0] => [L][L][C]
[1] => RazorLeaf
[2] =>
[3] => 50
)
Array
(
[0] => [C][C]
[1] => Pontapé
[2] =>
[3] => 20
)
To include the language in the output...
$output = [];
foreach($result as $language => $index){
foreach($index['a'] as $key => $value){
$data = [];
foreach ( $index as $key1 => $value1) {
$data[] = $index[$key1][$key];
}
$data[] = $language;
$output[] = $data;
}
}
print_r($output);
Gives (partial output)...
Array
(
[0] => [C][C]
[1] => Tackle
[2] =>
[3] => 20
[4] => en
)

Array inside array or nested array

I have an array like below: all the values I am getting one array only, but I don't want this way. This is the best way to do so, in php or jQuery both languages are ok for me
Array
(
[0] => Array
(
[val] => facebook
)
[1] => Array
(
[val] => snapchat
)
[2] => Array
(
[val] => instagram
)
[3] => Array
(
[expenses] => 986532
)
[4] => Array
(
[expenses] => 45456
)
[5] => Array
(
[expenses] => 56230
)
[6] => Array
(
[social_id] => 15
)
[7] => Array
(
[social_id] => 16
)
[8] => Array
(
[social_id] => 17
)
)
and I want to output like this..
$result = array(
array(
"val" => "Facebook",
"expenses" => "84512",
"social_id" => 1
),
array(
"val" => "Instagram",
"expenses" => "123",
"social_id" => 2
)
);
but this should be dynamic, the length of the above array can be varies
You can merge the arrays to one and use array_column to get all vals or expenses in a separate array.
Then foreach one array and build the new array with the key.
//$a = your array
// Grab each column separate
$val = array_column($a, "val");
$expenses= array_column($a, "expenses");
$social_id = array_column($a, "social_id");
Foreach($val as $key => $v){
$arr[] = [$v, $expenses[$key], $social_id[$key]];
}
Var_dump($arr);
https://3v4l.org/nVtDf
Edit updated with the 'latest' version of the array. My code works just fine with this array to without any changes.
to get that array style you can do it by hand for each array
function test(array ...$arr)
{
$result = array();
foreach ($arr as $key => $pair) {
foreach ($pair as $item => $value) {
$result[$item] = $value;
}
}
return $result;
}
$arr1 = test( ['facebook' => 1], ['expenses' => 100]);
print_r($arr1);
/* Array (
[facebook] => 1,
[expenses] => 100
)
*/
$arr2 = test( $arr1, ['more info' => 'info'] );
print_r($arr2);
/* Array (
[facebook] => 1,
[expenses] => 100,
[more info] => info
)
*/
you can pass it any number of
['Key' => 'Pair']
array('Key' => 'Pair')
or even a previous made array and it will add them up into 1 big array and return it

Multidimensional associative array: how to find array with same value?

I'm currently looking for a solution to this problem:
if I have something like that:
Array
(
[0] => Array
(
[id] => 1
[name] => Timer
)
[1] => Array
(
[id] => 2
[name] => Tub
)
[3] => Array
(
[id] => 1
[name] => Paper
)
[4] => Array
(
[id] => 4
[name] => Puppy
)
)
The goal I'd like to reach here is create a new array which contains the arrays with the same ID. So basically, at the end I'm gonna have two arrays: the first will contain element with different IDs and the second will contain element with the same ID.
Any tips? Thank you in advance!
One way is by mainly using array_filter()
// Gather ids and count
$id = array_count_values(array_column($array, 'id'));
// Filter not unique
$notUnique = array_filter($array, function($e) use ($id) {
return ($id[$e['id']] > 1);
});
// Filter unique
$unique = array_filter($array, function($e) use ($id) {
return !($id[$e['id']] > 1); // or ($id[$e['id']] == 1)
});
// Print result
print_r($notUnique);
echo '<br>';
print_r($unique);
Try this
<?php
$array = array(
array('id' => 1,'name' => 'Timer'),
array('id' => 2,'name' => 'Tub'),
array('id' => 1,'name' => 'Paper'),
array('id' => 4,'name' => 'Puppy')
);
$new = array();
foreach($array as $r)$new[$r['id']][] = $r['name'];
echo '<pre>';print_r($new);
?>
Output
Array
(
[1] => Array
(
[0] => Timer
[1] => Paper
)
[2] => Array
(
[0] => Tub
)
[4] => Array
(
[0] => Puppy
)
)

php merge 2 arrays into one associative array

Using PHP I need to merge 2 arrays (of equal length into one associative array) here is an excerpt from my current data set:
[1] => Array
(
[0] => C28
[1] => C29
)
[2] => Array
(
[0] => 1AB010050093
[1] => 1AB008140029
)
both elements [1] and [2] are actually a lot longer than just 2 sub-elements (like I said, this is an excerpt).
The deal is that "C28" in the first array corresponds to "1AB010050093" in the second array, and so on... The result I need is to create a new associative array that looks like this:
[1] => Array
(
['ref'] => C28
['part'] => 1AB010050093
)
[2] => Array
(
['ref'] => C29
['part'] => 1AB008140029
)
and so on...
If you are willing to compromise with an array structure like this:
array(
'C28' => '1AB010050093',
'C29' => '1AB008140029'
);
Then you can use the array_combine() (Codepad Demo):
array_combine($refNumbers, $partIds);
Otherwise, you'll need to use a foreach (Codepad Demo):
$combined = array();
foreach($refNumbers as $index => $refNumber) {
if(!array_key_exists($index, $partIds)) {
throw OutOfBoundsException();
}
$combined[] = array(
'ref' => $refNumber,
'part' => $partIds[$index]
);
}
If you're using PHP 5.5+, there is a new method called array_column(), which will get all of the values in a particular column. That could potentially be used, although I think just a simple foreach loop will probably still be your best bet.
How about:
$arr1 = array(
0 => 'C28',
1 => 'C29',
);
$arr2 = array(
0 => '1AB010050093',
1 => '1AB008140029',
);
$result = array();
for ($i=0; $i<count($arr1); $i++) {
$result[] = array('ref' => $arr1[$i], 'part' => $arr2[$i]);
}
print_r($result);
ouptut:
[1] => Array
(
[0] => C28
[1] => C29
)
[2] => Array
(
[0] => 1AB010050093
[1] => 1AB008140029
)

Integration of two fields in a database column

Please see my DEMO and answer my question: why date in values html on offset 2 not as date and it is a number?
DEMO: http://codepad.viper-7.com/r9FYnb
$data = array();
$data_1 = $_POST['data_1'];
$static = $_POST["static"];
foreach($static as $idx=>$val){
$data[] = array(
'data_1' => json_encode(Array($data_1[$idx*2],$data_1[$idx]*2+1)),
'static' => $static[$idx]
);
}
This is output:
Array
(
[0] => Array
(
[data_1] => ["2011\/8\/02",4023] **//4023 !?**
[static] => 12
)
[1] => Array
(
[data_1] => ["2011\/8\/09",4023] **// 4023!?**
[static] => 34
)
[2] => Array
(
[data_1] => ["2011\/8\/16",4023] **// 4023 !?**
[static] => 56
)
)
I'm not certain what you are trying to do here, but I see an inconsistency between how you manipulate $idx
'data_1' => json_encode(Array($data_1[$idx*2],$data_1[$idx]*2+1)),
// -----^^^^^^^^-------^^^^^^^^^^^^
For the second offset, perhaps you intend to modify $idx inside the []
'data_1' => json_encode(Array($data_1[$idx*2],$data_1[($idx*2)+1])),
// ---------------------^^^^^^^^^^^^
Sample output after modifying your demo:
Array
(
[0] => Array
(
[data_1] => ["2011\/8\/02","2011\/8\/08"]
[static] => 12
)
[1] => Array
(
[data_1] => ["2011\/8\/09","2011\/8\/15"]
[static] => 34
)

Categories