Create data set in php (loop) - php

Hello i am trying to create data set like
Expected output:-
Array
(
[0] => Array
(
[sku] => sku
[variant_option_one_name] => Color
[variant_option_one_value] => Cyan
),
[1] => Array
(
[sku] => sku
[variant_option_one_name] => Color
[variant_option_one_value] => Red
)
)
but i am not sure what is missing in code.
Here is the code
$array = array(
0 => array(
'id_product_attribute' => '17615',
'id_product' => '2295',
'reference' => '',
'available_date' => '0000-00-00',
'vend_id' => null,
'id_shop' => '1',
'id_attribute_group' => '1',
'is_color_group' => '1',
'group_name' => 'Color',
'attribute_name' => 'Cyan',
'id_attribute' => '1',
),
1 => array(
'id_product_attribute' => '17616',
'id_product' => '2295',
'reference' => '',
'available_date' => '0000-00-00',
'vend_id' => null,
'id_shop' => '1',
'id_attribute_group' => '1',
'is_color_group' => '1',
'group_name' => 'Color',
'attribute_name' => 'Red',
'id_attribute' => '21',
),
);
$ids = array();
foreach ($array as $combinations) {
$ids['sku'] = 'sku';
$ids['variant_option_one_name'] = $combinations['group_name'];
$ids['variant_option_one_value'] = $combinations['attribute_name'];
}
print_r($ids);//
Here i am getting
Array
(
[sku] => sku
[variant_option_one_name] => Color
[variant_option_one_value] => Red
)
The above output i am getting. Seems like data is overwrite
Any correction to get both the data ?
I do not get both the colors in array. It
Thankyou

You're absolutely right, the values are being overwritten each time.
What you need to do is, each time you loop you should create a new array containing your values, and then assign that array to a new index inside the main array (so you get an array of arrays, like the expected output you've shown):
foreach ($array as $combinations) {
$arr = array();
$arr['sku'] = 'sku';
$arr['variant_option_one_name'] = $combinations['group_name'];
$arr['variant_option_one_value'] = $combinations['attribute_name'];
$ids[] = $arr;
}
Live Demo: http://sandbox.onlinephpfunctions.com/code/3a0cf7f8cbb994ef4192c1e23493bef397785937

foreach ($array as $combinations) {
array_push ($ids, [
'sku' => 'sku',
'variant_option_one_name' => $combinations['group_name'],
'variant_option_one_value' => $combinations['attribute_name']
]);
}

Related

Split array in php

I am getting result in php. I want to split the array to get each value in variable or list. The result is like this:
Array
(
[success] => 1
[result] => Array
(
[id] => 12345678ABCDEXXX
[userid] => 2950
[system_user_id] => 76
[coin] => TRX
[amount] => 11.110000
[feePercent] => 0
[feeAmount] => 0
[memoTag] =>
[networkFee] => 0
[address] => TESTADDRESSHERE
[confirmations] => 0
[callBackUrl] => www.xyz.com/test
[transactionStatus] => WaitingForTransaction
[transactionType] => Deposit
[createdOn] => 1643692929
[modifiedOn] => 1643692929
[expiredon] => 1644988929
[description] => This is description
)
)
how to split and get every value?
This may answer your question
https://www.php.net/manual/en/function.extract.php
extract($array)
Php Multidimensional array to variable
<?php
$array = Array
(
'success' => '1',
'result' => array(
'id' => '12345678ABCDEXXX',
'userid' => '2950',
'system_user_id' => '76',
'coin' => 'TRX',
'amount' => '11.110000',
'feePercent' => '0',
'feeAmount' => '0',
'memoTag' => '',
'networkFee' => '0',
'address' => 'TESTADDRESSHERE',
'confirmations' => '0',
'callBackUrl' => 'www.xyz.com/test',
'transactionStatus' => 'WaitingForTransaction',
'transactionType' => 'Deposit',
'createdOn' => '1643692929',
'modifiedOn' => '1643692929',
'expiredon' => '1644988929',
'description' => 'This is description'
)
);
function extractMultidimentional($array){
foreach ($array as $key => $value) {
if(is_array($value)){
extractMultidimentional($value);
}else{
global ${$key};//Set as global
${$key} = $value;//Assign with its value
}
}
}
extractMultidimentional($array);
// Now you can call each key as a variable
echo $success;//1
echo $system_user_id;//76
echo $expiredon;//1644988929
If you have multidimensional array and those have same key then the variable will store last array value
You can use array_chunk like this
$array = array('value -1', 'value 2', 'value 3', 'value 4', 'value 5','value -6','value -7');
$newArrays = array_chunk($array,2); // apply array chunk
echo "";
// print the first segment (position) array after splitting that array.
print_r($newArrays[0]);

how to access value form array

please find below contains array in php
$data = array ( 'questions' => array ( 1 =>
array (
'section_id' => '61',
'questionid' => '2035',
'time_spent' => '0',
),
2 =>
array (
'section_id' => '61',
'questionid' => '2036',
'time_spent' => '0',
),
3 =>
array (
'section_id' => '61',
'questionid' => '2037',
'time_spent' => '0',
),
),)
how can i access section_id, and time_spent data from array
Please use the below code : Also see this link
foreach($data as $key => $values){
foreach ($values as $ikey => $secArr) {
# code...
$section_id = $secArr['section_id'];
$time_spent = $secArr['time_spent'];
echo 'Section Id: '.$section_id.' | Time Spend:'.$time_spent.'</br>';
}
}
I hope it will helps you.

Inserting a new key if a particular key value matches in both the arrays

$array1 = array(
[0] => array(
'id' => 'gdye6378399sjwui39',
'name' => 'Plate 1'
),
[1] => array(
'id' => 'xyz6378399sjwui39',
'name' => 'Plate 2'
),
[2] => array(
'id' => 'tr2e6378399sjwui39',
'name' => 'Plate 3'
)
)
and another array
$array2 = array(
[0] => array(
'id' => 'gdye6378399sjwui39',
'ETA' => '8'
),
[1] => array(
'id' => 'tr2e6378399sjwui39',
'ETA' => '9'
)
[2] => array(
'id' => 'xyz6378399sjwui39',
'ETA' => '5'
)
)
I want to compare the two arrays. I am doing it like this way:-
if(!empty($array2))
{
foreach($array1 as $ck => $cl)
{
foreach($array12 as $ued){
if($cl['id'] == $ued['id'])
{
$array1[$ck]['ETA'] = $ued['ETA'];
break;
}
}
}
What are the other better ways to do this? The order of the two arrays may vary, and so does the size.
If you index the second array by the id (using array_column()) you can get away without using the inner foreach() and just use isset()...
$match = array_column($array2, null, 'id');
foreach ( $array1 as $ck=>$cl) {
if ( isset($match[$cl['id']]) ) {
$array1[$ck]['ETA'] = $match[$cl['id']]['ETA'];
}
}
print_r($array1);

Problems with merging arrays

I have a number of arrays like the one below. These are the result of data retrieved from the database. I need the final array to have the structure mentioned because I need to foreach loop each 'notes' in the successive code. I can't use a for loop only.
array('title' => 'Testing',
'content' => 'some text',
'created' => 'time',
'tags' => array(array('title' => 'hello')),
)
array('title' => 'Testing',
'content' => 'some text',
'created' => 'time',
'tags' => array(array('title' => 'hello')),
)
I want to merge all of these in an array of the format:
array(
array('notes' =>
array('title' => 'Testing',
'content' => 'some text',
'created' => 'time',
'tags' => array(array('title' => 'hello')),
),
),
array('notes' =>
array('title' => 'Testing',
'content' => 'some text',
'created' => 'time',
'tags' => array(array('title' => 'hello')),
),
),
);
I've tried many PHP functions but none gave me the result I want. Can someone help me please? Is there a built-in PHP function that can do this? Can someone show me an example.
Thanks.
If I'm understanding your question correctly, all you actually want to do is place each of your array elements into another array with the key notes and the value being that of the element (another array).
In which case either using foreach or array_map will do.
$newArray = array_map(function($v) { return ['notes' => $v]; }, $array);
Or using foreach (the more verbose way)...
foreach($array as $value) {
$newArray[] = ['notes' => $value];
}
this is a comment i want the formatting...
You have asked for an 'array' of 'array entries' where each entry
is an array
each array has a key of 'notes' and an associated data array.
I think the 'tags' part of you structure would be easier to use without the extra level of 'nesting'.
Here is the code to create and display the 'wanted' output with the 'tag' entry changed:
$wanted = array(
array('notes' =>
array('title' => 'Testing 1',
'content' => 'some text 1',
'created' => date('Y-m-d H:i:s'),
'tags' => array('title' => 'hello',
'tagFoo' => 'foo' ),
),
),
array('notes' =>
array('title' => 'Testing 2',
'content' => 'some text 2',
'created' => date('Y-m-d H:i:s'),
'tags' => array('title' => 'hello',
'tagBar' => 'bar'),
),
),
);
echo '<pre>';
print_r($wanted);
echo '</pre>';
Here is the output:
Array
(
[0] => Array
(
[notes] => Array
(
[title] => Testing 1
[content] => some text 1
[created] => 2015-01-04 15:39:34
[tags] => Array
(
[title] => hello
[tagFoo] => foo
)
)
)
[1] => Array
(
[notes] => Array
(
[title] => Testing 2
[content] => some text 2
[created] => 2015-01-04 15:39:34
[tags] => Array
(
[title] => hello
[tagBar] => bar
)
)
)
)
one possibilyti is to do:
foreach($tags as $key => $note){
$note["created"] = $created[$key]; //if created is an array
$note["created"] = $created; //if created is a string
}

Searching in a multi-dimensional array (PHP)

I'm having a problem lately that's driving me crazy. I have a multi-dimensional array like this:
$a = array(
'db' => array(
'0' => array(
'id' => '1',
'name' => 'test',
'cat' => array(
'a' => '15',
'b' => '20',
'c' => '30'
),
'canvas' => '2'
),
'1' => array(
'id' => '2',
'name' => 'test2',
'cat' => array(
'a' => '15',
'b' => '20',
'c' => '30'
),
'canvas' => '2'
)
'2' => array(
'id' => '3',
'name' => 'test',
'cat' => array(
'a' => '50',
'b' => '40',
'c' => '90'
),
'canvas' => '1'
)
)
);
And i want to search on it using a function like this: search('canvas = 1');
That would return all the arrays, child of db, that have a key canvas with the value of 1. Or, for example:
search('a = 15');
Would return all arrays that have a key, child of cat, named a and with a value of 15.
$a = array(
'db' => array(
'0' => array(
'id' => '1',
'name' => 'test',
'cat' => array(
'a' => '15',
'b' => '20',
'c' => '30'
),
'canvas' => '2'
),
'1' => array(
'id' => '2',
'name' => 'test2',
'cat' => array(
'a' => '15',
'b' => '20',
'c' => '30'
),
'canvas' => '2'
),
)
);
//checks if array $array contains element with $searchKey key, and $searchVal value
function arrayContains($array, $searchVal, $searchKey) {
if (!is_array($array))
return false;
foreach ($array as $key => $value) {
if ($key === $searchKey && $searchVal === $value)
return true;
if (is_array($value) && arrayContains($value, $searchVal, $searchKey))
return true;
}
return false;
}
function search($a, $search) {
list($searchKey, $searchVal) = explode('=', $search);
$result = array();
foreach($a as $val) {
if (arrayContains($val, $searchVal, $searchKey))
$result[] = $val;
}
return $result;
}
print_r(search($a['db'], "a=15"));
print_r(search($a['db'], "canvas=1"));
Which produces this output(outputs sub-arrays of $a['db'] which contain searched key=>value pair):
Array
(
[0] => Array
(
[id] => 1
[name] => test
[cat] => Array
(
[a] => 15
[b] => 20
[c] => 30
)
[canvas] => 2
)
[1] => Array
(
[id] => 2
[name] => test2
[cat] => Array
(
[a] => 15
[b] => 20
[c] => 30
)
[canvas] => 2
)
)
Array
(
[0] => Array
(
[id] => 3
[name] => test
[cat] => Array
(
[a] => 50
[b] => 40
[c] => 90
)
[canvas] => 1
)
)
Just check the below link if this can help you -
http://php.net/manual/en/function.array-search.php
It contains detailed documentation of php function array_search() and various user codes for searching in multi-dimensional array along with user reviews.
function search($array, $canvas)
{
$result = array();
foreach ($array as $k1 => $v1) {
foreach ($v1 as $k2 => $v2) {
if ($v2['canvas'] == $canvas) {
$result[] = $array[$k1][$k2];
}
}
}
return $result;
}
// $a = your array
print_r(search($a, 1));

Categories