Inserting a multidimensional array into another multidimensional array - php

$stack = array(
'name' => 'some data',
'caption' => 'some data',
'published' => 'some data',
'updated_at' => 'some data',
'updated_by' => 'some data'
);
$data = array('album_id' => 'someID');
How do i insert the data array into the stack array?
update: i tried array_unshift but it inserted the $data array in a second dimension within the multi but i want it at the same level as the others.
also, one more question
if I have another array like data and i want to insert it into the 3rd position how would i do that?

Try
$stack = $stack + $data;
Or
$stack =array_merge($stack, $data);
If you want to add $data to the 3rd position in $stack
$chunks = array_chunk($stack, 2, true);
$stack = array_shift($chunks);
$stack += $data;
foreach ($chunks as $chunk) { $stack += $chunk; }

Related

Searching within PHP multi dimensional array to return results within parent array

I'm looking for a function to search for a matching keyword in a multi dimensional array and return the corresponding name and path values.
$search_array = array(
array(
'keywords' => array('apple', 'orange'),
'name' => 'Url One',
'path' => 'http://www.urlone.com'
),
array(
'keywords' => array('bananna'),
'name' => 'Url Two',
'path' => 'http://www.urltwo.com'
)
)
If there's a better way to structure this array to make it simpler the that would also be great, thanks
This can be accomplished using array filter:
$matches = array_filter($search_array, function($array){
return in_array('bananna', $array['keywords']);
});
Or using a foreach loop:
$matches = [];
foreach ($search_array as $key => $array) {
if (in_array('apple', $array['keywords'])) {
$matches[$key] = $search_array[$key];
}
}

Adding data to array through loop php

I have a problem where I am getting data from database and need to put that in an array. The array is associative and I am not sure about this practice so I thought I should ask the community. Is this the correct way of adding data to array? The array is for the radio buttons that will be provided to the helper class in prestashop. The array structure is important. This is the var_dump array structure which I have in $options_break2.
$options_value = array();
$options = array();
for($z=0; $z<sizeof($options_break2); $z++)
{
$options_value = array_push($options_value,
array(
"id" => $options_break2[$z],
"name" => $options_break2[$z],
"label" => $options_break2[$z],
)
);
}
$options = array_push($options, $options_value);
What I want is that the array should contain something like:
$example = array(
array(
'id_option' => 'some value',
'name' => 'some value',
),
array(
'id_option' => 'some value',
'name' => 'some value',
),
);
Actually you don't need to use array_push and array() if your PHP version is above 5.6, and you can improve your loop by using the foreach loop:
$options_value = [];
foreach ($options_break2 as $opt) {
$options_value[] = [
"id_option" => $opt, // some_value
"name" => $opt // some_value
];
}
$options = $options_value; // you don't really need this

How to add a key value pair at the end of a multidimensional array?

I am working on array for a project and I want to know how I can add a key value pair at the end of an array.
So here are the elements:
1st array
$items = array(
array('id' => '1', 'desc'=>'Canadian-Australian Dictionary', 'price'=>24.95),
array('id' => '2', 'desc'=>'As-new parachute (never opened)', 'price'=> 1000),
array('id'=>'3', 'desc'=>'Songs of the Goldfish (2CD set)', 'price'=> 19.99));
2nd array:
$cart = array(
array('id' => '1','quantity'=>2)
);
So basically what I want to know is how can I add values from 1st array to 2nd array based on the id to have a array like this one.
final array i want to get:
$itemDetail = array(
array('id' => '1', 'desc'=>'Canadian-Australian Dictionary', 'price'=>24.95, 'quantity'=> 1)
);
You can do it simple with loop:
$result = [];
foreach ($cart as $attributes) {
foreach ($items as $item) {
if ($item['id'] == $attributes['id']) {
$result[] = $item + $attributes;
}
}
}
var_dump($result);
Work For both array look like above in sequence id start with 1
$items = array(
array('id' => '1', 'desc'=>'Canadian-Australian Dictionary', 'price'=>24.95),
array('id' => '2', 'desc'=>'As-new parachute (never opened)', 'price'=> 1000),
array('id'=>'3', 'desc'=>'Songs of the Goldfish (2CD set)', 'price'=> 19.99));
$cart = array(
array('id' => '1','quantity'=>2)
);
function my_array_merge(&$array1, &$array2) {
$result = Array();
foreach($array1 as $key => &$value) {
$result[$key] = array_merge($value, $array2[$key]);
}
return $result;
}
$array = my_array_merge($items, $cart);
print_r($array);

PHP Explode String Into Multiple Arrays

I have the following string: "1,3,4,7" which I need to explode into an Array in the following format:
$data = array(
array(
'id' => 1
),
array(
'id' => 3
),
array(
'id' => 4
),
array(
'id' => 7
),
);
This seems to be causing me a lot more pain than I'd have thought. Can anyone kindly assist please?
You can use a combination of array_map() and explode(): First you create an array with the values and than you map all these values to the format you need in a new array.
Something like:
$vals = "1,3,4,7";
$map = array_map(function($val) {
return array('id' => $val);
}, explode(',', $vals));
var_dump($map);
An example.
Firstly you explode the string to get the values in an array. Then you iterate through the array and set the data as array to another array
$string = "1,2,3,4";
$array = explode(",", $string);
$data = array();
foreach($array as $arr){
$data[] = array('id' => $arr);
}
<?php
$myArray=explode(",","1,3,5,7");
$result=array();
foreach($myArray as $key=>$arr)
{
$result[$key]['id']=$arr;
}
print_r($result);
?>
Here is a thinking-outside-the-box technique that doesn't require a loop or iterated function calls.
Form a valid query string with the desired structure and parse it. The empty [] syntax will generate the indexes automatically.
Code: (Demo)
$vals = "1,3,4,7";
$queryString = 'a[][id]=' . str_replace(',', '&a[][id]=', $vals);
parse_str($queryString, $output);
var_export($output['a']);
Output:
array (
0 =>
array (
'id' => '1',
),
1 =>
array (
'id' => '3',
),
2 =>
array (
'id' => '4',
),
3 =>
array (
'id' => '7',
),
)

matching multidimensional arrays by key value, preserving other values

I have an array that contains data in the following format:
$myArray = array(
array(
'id' = 1,
'title' = 'the first entry',
'data' = 'additional data'
),
array(
'id' = 2,
'title' = 'the third entry',
'data' = 'some more data'
),
array(
'id' = 3,
'title' = 'the second entry',
'data' = 'other important stuff'
)
);
(An array containing about 12 child arrays in total). This data needs to be split into two rows for displaying on my page, based on the title attribute. I know what titles I want on the first row, and which ones for the second row. So I have another array like this:
$firstRow = array('the first entry', 'the second entry');
$secondRow = array('the third entry');
So what I need to do is throw these 3 arrays, $myArray, $firstRow, $secondRow into a function which will output a new ordered array which preserves the other attributes (the id and data keys in my example) like the following:
$newArray = array(
'firstRow' => array(
array(
'id' = 1,
'title' = 'the first entry',
'data' = 'additional data'
),
array(
'id' = 2,
'title' = 'the second entry',
'data' = 'some more data'
)
),
'secondRow' => array(
array(
'id' = 3,
'title' = 'the third entry',
'data' = 'other important stuff'
)
)
);
I have some ideas, and I know there are various functions like array_intersect(), but I'm not sure which is the best to use? Hopefully someone has a quick and easy solution to this. Thanks.
Use a foreach to loop over the titles array, and create a new array inside the loop, depending on the title value:
function groupTitlesintoArrays($myArray, $firstRow, $secondRow) {
$result = array();
foreach ($myArray as $innerArray) {
foreach ($firstRow as $row) {
if ($row == $innerArray['title']) {
$result['firstRow'][] = $innerArray;
}
}
foreach ($secondRow as $row) {
if ($row == $innerArray['title']) {
$result['secondRow'][] = $innerArray;
}
}
}
return $result;
}
Demo

Categories