I have an array like this
Array
(
[0] => Array
(
[catid] => 1
[percentage] => 4
[name] => Access Control
)
[1] => Array
(
[catid] => 7
[percentage] => 1
[name] => Audio Video
)
[2] => Array
(
[catid] => 5
[percentage] => 1
[name] => Home Automation
)
)
tho this array i want to add a pair of catid,percentageand name as another
array on the next key eg:
[3] => Array
(
[catid] => 7
[percentage] => 0
[name] => 'some name'
)
Here is my code
//another array
$id=array('1','2',....n);
//$data is my original array
foreach($id as $key=>$value){
$data[]['catid']=$value;
$data['percentage'][]='0';
$data['name'][]='Some name';
}
But it will give wrong output.
//another array
$id=array('1','2',....n);
$i = count($data);
//$data is my original array
foreach($id as $key=>$value){
$data[$i]['catid']=$value;
$data[$i]['percentage']='0';
$data[$i]['name']='Some name';
$i++;
}
The only thing you need to do is:
$yourArray[] = [
'catid' => 7,
'percentage' => 0,
'name' => 'some name'
];
You're building the array wrong:
This pushes a NEW element onto the main $data array, then assigns a key/value of catid/$value to that new element:
$data[]['catid']=$value;
Then you create a new top-level percentage, and push a zero into it, and ditto for name:
$data['percentage'][]='0';
$data['name'][]='Some name';'
You can't build a multi-key array like this. You need to build a temporary array, then push the whole thing onto the main array:
$temp = array();
$temp['catid'] = $value;
$temp['percentage'] = 0;
$temp['name'] = 'Some name';
$data[] = $temp;
Or in shorthand notation:
$data[] = array('catid' => $value, 'percentage' => 0, 'name' = 'Somename');
You can use array_push
$a1 = array(array('catid' => '1', 'percentage' => '4', 'name' => 'Access Control'));
$a2 = array('catid' => '7', 'percentage' => '0', 'name' => 'Some Name');
array_push($a1 ,$a2);
print_r($a1);
Related
I want to remove key 0 from parent array and set child array as parent.
Here I will get single value so one array is ok for me.
My current array looks like this
Array
(
[0] => Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
)
I want it like below. expected result
Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
For this I tried like below but no success.
$new = array();
foreach ($data as $v){
$new = array_merge($new , array_values($v)) ;
}
but in my code it's removed key e.g id,api_key, etc....
I need key name also in my new array. please suggest
Remove the array_values
Solution
<?php
$test = array(
array
(
'id' => 3,
'api_key' => 'acount266'
)
);
$new = array();
foreach($test as $v){
$new = array_merge($new, $v);
}
var_dump($new);
Result
array(2) {
["id"]=>
int(3)
["api_key"]=>
string(9) "acount266"
}
According to documentation of PHP as mentioned
reset() function returns the value of the first array element, or
FALSE if the array is empty.
$array = array(
array(
'id' => 3,
'api_key' => 'acount266',
'auth_domain' => 'Tester26',
'database_url' => 'vcc.test.acc+27#gmail.com',
'project_id' => '12345',
'storage_bucket' => '',
'secret_key_path' => '',
'fcm_server_key' => 1,
'messaging_sender_id' => 0,
'key_phrase' => '',
'disable' => 0,
'created' => '',
'updated' => ''
)
);
print_r(reset($test));
I tried this:
$arr = array();
foreach ($examples as $example) {
foreach ($example as $e) {
array_push($arr, $e);
}
}
Don't overcomplicate this, reassigning the first element to the parent array is quick and easy:
<?php
$array =
array (
0 =>
array (
'first' => 'Michael',
'last' => 'Thompson'
)
);
$array = $array[0];
var_export($array);
Output:
array (
'first' => 'Michael',
'last' => 'Thompson',
)
Or:
$array = array_shift($array);
Below is my array which i have printed:-
I want only the product_image from the array in loop
Array
(
[0] => Array
(
[product_option_id] => 247
[product_id] => 66
[product_option_value] => Array
(
[0] => Array
(
[product_option_value_id] => 42
[color_product_id] => 54
[name] => Pink
[product_image] => catalog/demo/teddy/03.jpg
[image] => http://192.168.15.9/Kids_stores/image/cache/catalog/axalta-ral-3015-light-pink-polyester-30-matt-powder-coating-20kg-box--1447-p-50x50.jpg
[price] =>
[price_prefix] => +
)
[1] => Array
(
[product_option_value_id] => 41
[color_product_id] => 67
[name] => Light Brown
[product_image] => catalog/Teddies/12-Baby-teddy/05.jpg
[image] => http://192.168.15.9/Kids_stores/image/cache/catalog/option-color/light_brown-50x50.jpg
[price] =>
[price_prefix] => +
)
[2] => Array
(
[product_option_value_id] => 43
[color_product_id] => 68
[name] => Cream
[product_image] => catalog/Teddies/12-Baby-teddy/11.jpg
[image] => http://192.168.15.9/Kids_stores/image/cache/catalog/option-color/cream-images-50x50.jpg
[price] =>
[price_prefix] => +
)
)
[option_id] => 5
[name] => COLOR
[type] => image
[value] =>
[required] => 0
)
)
Try this,
foreach($array as $val)
{
echo $val['product_image'];
}
Solution for your edited input:-
$image_array = array();
foreach ($your_array as $arr){
$image_array[] = array_column($arr['product_option_value'],'product_image');
}
Output:- https://eval.in/657966
You can take the array array_column and make it like this
$records = array (
array (
// your array
)
);
$variable = array_column($records, 'image');
echo $variable;
<?php $samples=$data['options'][0][product_option_value];
$product_image = array_column($samples, 'product_image');
echo'<pre>'; print_r($product_image );
?>
foreach($array as $key => $val){
if($key == 'product_image'){
echo "<img src='".$val."' />";
}
}
Try
You have to foreach the inner array:
foreach($array[product_option_value] as $val)
{
echo $val['product_image'];
}
Solution One:
<?php
$req_image=array();
$req_image[] = array_column($resultant_array, 'product_image');
print_r($req_image); // This will print all the images that are grouped under the array().
?>
Example:
The below is the PHP code and the sample output that you can obtain using the array_column().
PHP:
<?php
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe'
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith'
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones'
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe'
)
);
$lastNames = array_column($records, 'last_name', 'id');
Output:
If we call print_r() on $lastNames, you’ll see a resulting array that looks a bit like this:
Array
(
[2135] => Doe
[3245] => Smith
[5342] => Jones
[5623] => Doe
)
Solution Two: (As per requirement at last)
You can iterate the single key value alone in the foreach so that you can get the required parameter that you need.
foreach($resultant_array as $single_array)
{
foreach($single_array['product_option_value'] as $inner_array)
{
echo $inner_array['product_image']; // This will print the u=mage name that you need.
}
}
If you want one specified key and want minimal assumptions about array structure shoud use array_walk_recursive like this
$result = [];
array_walk_recursive($input,function ($value,$key) use (&$result) {
if ( 'product_image' == $key) {
$result[] = $value;
}
});
I have an object with several properties that creates a multi dimensional array. I'm trying to figure out how to create a new array that combines two seperate objects into one. It would go from this:
array(
object_1(
'id' => '1',
'name' => 'joe'
etc....),
object_2(
'id' => '2',
'name' => 'jessica',
etc....)
object_3(
'id' => '3',
'name' => 'tim',
etc....)
object_4(
'id' => '4',
'name' => 'tammy',
etc....)
);
And become:
array(
object_1(
'id' => '1',
'name' => 'joe',
etc...
'id2' = > '2',
'name2' => 'jessica',
etc...)
object_2(
'id' => '3',
'name' => 'tim',
etc...
'id2' = > '4',
'name2' => 'tammy',
etc...)
So, I need to combine the data from alternating elements, and also change the key in all the second objects so it doesn't match the first. Make sense? Sorry if it doesn't, I'll try to clarify if you need!
Thanks for any help....
EDIT: first two stdclass objects according to print_r:
[results] => Array
(
[0] => stdClass Object
(
[email] => sample#info.com
[message] => Create another test
[image] => 138.png
[fid] => 53
)
[1] => stdClass Object
(
[email] => info#sample.com
[message] => none
[image] => 330.jpg
[fid] => 52
)
and I want it to become:
[results] => Array
(
[0] => stdClass Object
(
[email] => sample#info.com
[message] => Create another test
[image] => 138.png
[fid] => 53
[email2] => info#sample.com
[message2] => none
[image2] => 330.jpg
[fid2] => 52
)
Does that clarify?
Assuming it's actually a multi-dimensional array, not an array of objects, this should do it:
$new_array = array();
for ($i = 0; $i < count($array); $i +=2) {
$new_array[] = $array[$i];
foreach ($array[$i+1] as $key => $value) {
$new_array[$i/2][$key.'2'] = $value;
}
}
EDIT: For an array of objects, it becomes:
$new_array = array();
for ($i = 0; $i < count($array); $i +=2) {
$new_array[] = $array[$i];
foreach (get_object_vars($array[$i+1] as $key => $value) {
$new_array[$i/2]->{$key.'2'} = $value;
}
}
This will only work for public properties.
You could do something like
for($i=0;$i<count($array);$i+=2) {
$id = $array[$i]['id'];
$name = $array[$i]['name'];
$id2 = $array[$i+1]['id'];
$name2 = $array[$i+1]['name'];
}
or
$newarray = array();
$j=0;
for($i=0;$i<count($array);$i+=2) {
$newarray[$j]['id'] = $array[$i]['id'];
$newarray[$j]['nae'] = $array[$i]['name'];
$newarray[$j]['id2'] = $array[$i+1]['id'];
$newarray[$j]['name2'] = $array[$i+1]['name'];
$j++;
}
I have to array and I want to merge this two array with a main key ( ID ) , and I would like to order alphabetically this NEW array ( the lastname field )
Array (
[0] =>
Array ( [id] => 172
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => accepted
)
[1] =>
Array (
[id] => 173
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => pending
) )
And this array
Array (
[1217330 ] =>
Array ( [firstname] => Philip
[lastname] => Audet
[birthdate] => 1995-07-17
[id] => 1217330
)
[232323] =>
Array ( [firstname] => Frédéric
[lastname] => Bouchard-Dubé
[birthdate] => 1995-07-17
[id] => 232323
)
And I would like to have this
[0] =>
Array ( [id] => 172
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => accepted
[firstname] => Philip
[lastname] => Audet
)
[1] =>
Array (
[id] => 173
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => pending
[firstname] => Philip
[lastname] => Audet
) )
I wont want to have the birthdate index for THIS array, I only want to get the firstname and the lastname from the second array. So I want to math the index USER_ID ( first_table) with ID (second table). I also want to order this new table alphabetically with the lastname (in my exemple, I don't need to sort it alphabetically, but I will need to do this )
Can some one can help me please ? Thx
Thx
This is doing what you are looking for. As your example is out of context you might need to take some different approaches, but I hope it will help you get the task done.
$behaviour = array(
array(
'id' => 172,
'user_id' => 1217330,
'behaviour_action_id' => 97,
'state' => 'accepted'
),
array(
'id' => 173,
'user_id' => 232323,
'behaviour_action_id' => 97,
'state' => 'pending'
),
);
$users = array(
1217330 => array(
'firstname' => 'Philip',
'lastname' => 'Audet',
'birthdate' => '1995-07-17',
'id' => 1217330
),
232323 => array(
'firstname' => 'Frédéric',
'lastname' => 'Bouchard-Dubé',
'birthdate' => '1995-07-17',
'id' => 232323
),
);
//we will collect the data in a new array
$combined = array();
//now we loop through all behaviours
foreach($behaviour as $key => $behaviourData){
//we look up the data which belongs to the user of this behaviour
$wantedUserData = $users[$behaviourData['user_id']];
//birthdate is unwanted
unset($wantedUserData['birthdate']);
//merge data
$combined[] = array_merge($behaviourData, $wantedUserData);
}
//order array
usort($combined,'cmp');
//voilà!
var_dump($combined);
//Comparison function used in usort above
function cmp($a, $b){
if ($a['lastname'] == $b['lastname']){
return 0;
}
return ($a['lastname'] < $b['lastname']) ? -1 : 1;
}
$arr1 = array (
array("id"=>172, "user_id"=>1217330, "behaviour_action_id"=>97, "state"=>"accepted"),
array("id"=>173, "user_id"=>1217330, "behaviour_action_id"=>97, "state"=>"pending")
);
$arr2 = array(
"1217330" => array(
"firstname" => "Philip",
"lastname" => "Audet",
"birthdate" => "1995-07-17",
"id" => 1217330
),
"232323" => array (
"firstname" => "Frédéric",
"lastname" => "Bouchard-Dubé",
"birthdate" => "1995-07-17",
"id" => 232323
)
);
foreach($arr1 as $arr) {
$extra = $arr2[$arr["user_id"]];
unset($extra["birthdate"]);
$newarray[] = array_merge($extra, $arr);
}
print_r($newarray);
this one? (assuming $arr1 and $arr2 the given arrays)
$arr3 = array();
foreach($arr1 as $key=>$val) {
$arr3[$key] = $val;
$arr3[$key]["firstname"] = $arr2[$val["user_id"]]["firstname"];
$arr3[$key]["lastname"] = $arr2[$val["user_id"]]["lastname"];
}
echo "<pre>";
print_r($arr3);
echo "</pre>";
Well, I don't want to give a cooked-up code but this algorithm will do the job:
1) Loop through first array and create another array with user_id as key. like
$new_array[$array['user_id']] = array($array['id'], $array['state']...);
2) Loop through second array and unset() the key birthdate.
3) Use array_merge_recursive() and merge the two arrays.
I have two arrays:
Array
(
[0] => Array
(
[id] => 1
[type] => field
[remote_name] => Title
[my_name] => title
[default_value] => http%3A%2F%2Ftest.com
)
[1] => Array
(
[id] => 2
[type] => field
[remote_name] => BookType
[my_name] => book-type
[default_value] =>
)
[2] => Array
(
[id] => 3
[type] => value
[remote_name] => dvd-disc
[my_name] => dvd
[default_value] =>
)
)
Array
(
[title] => Test
[book-type] => dvd
)
I need to take each key in the second array, match it with the my_name value in the first array and replace it with the corresponding remote_name value of the first array while preserving the value of the second array.
There's got to be some carrayzy function to help!
EDIT: There will also be a few cases that the value of the second array will need to be replaced by the value of the first array's remote_name where the value of the second array matches the value of the first array's my_name. How can I achieve this?
EG: book-type => dvd should turn into BookType => dvd-disc
Like so?:
$first = array(
array(
'id' => 1,
'type' => 'field',
'remote_name' => 'Title',
'my_name' => 'title',
'default_value' => 'http%3A%2F%2Ftest.com',
),
array(
'id' => 2,
'type' => 'field',
'remote_name' => 'BookType',
'my_name' => 'book-type',
'default_value' => '',
),
array(
'id' => 3,
'type' => 'value',
'remote_name' => 'dvd-disc',
'my_name' => 'dvd',
'default_value' => '',
),
);
$second = array(
'title' => 'Test',
'book-type' => 'dvd',
);
$map = array('fields' => array(), 'values' => array());
foreach ($first as $entry) {
switch ($entry['type']) {
case 'field':
$map['fields'][$entry['my_name']] = $entry['remote_name'];
break;
case 'value':
$map['values'][$entry['my_name']] = $entry['remote_name'];
break;
}
}
$new = array();
foreach ($second as $key => $val) {
$new[isset($map['fields'][$key]) ? $map['fields'][$key] : $key] = isset($map['values'][$val]) ? $map['values'][$val] : $val;
}
print_r($new);
Output:
Array
(
[Title] => Test
[BookType] => dvd-disc
)
Explanation:
The first loop collects the my_name/remote_name pairs for fields and values and makes them more accessible.
Like so:
Array
(
[fields] => Array
(
[title] => Title
[book-type] => BookType
)
[values] => Array
(
[dvd] => dvd-disc
)
)
The second loop will traverse $second and use the key/value pairs therein to populate $new. But while doing so will check for key/value duplicates in $map.
Keys or values not found in the map will be used as is.
foreach($arr1 as &$el) {
$el['remote_name'] = $arr2[$el['my_name']];
}
unset($el);
I am not aware of such a carrayzy function, but I know how you could do it:
//$array1 is first array, $array2 is second array
foreach($array1 as $key => $value){
if (isset($value['remote_name'], $value['my_name']) && $value['remote_name'] && $value['my_name']){
$my_name = $value['my_name'];
if (isset($array2[$my_name])) {
$remote_name = $value['remote_name'];
$array2[$remote_name] = $array2[$my_name];
//cleanup
unset($array2[$my_name]);
}
}
}