Extracting from mulit-array and putting it into my own - php - php

I'm trying to extract data from a multidimensional array and then putting into one of my own so that I can load it into my database.
Source:
array( "ListOrdersResult" =>
array ( "Orders" =>
array( "Order" =>
array( [0] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
},
[1] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
}
)
)
)
To do this, I'm cycling through it like this - I have no issues with extracting data.
My code:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
$baseArray = $listOrderArray['ListOrdersResult']['Orders']['Order'][$i];
foreach($baseArray as $key => $value) {
if($key == "Title" || $key == "customer_id") {
//ADD TO multidimensional array
}
}
}
How I'm trying to structure it.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
The ultimate goal is to make it easier to load the information into the database by gathering the data by record and then loading it to the database rather than loading by creating an new record and then coming back and modifying that record. To me that seems like it would take more resources and has a higher chance of inconsistent data, but I'm new so I could be wrong.
Any help would be greatly appreciated.

You only have to unset keys you don't want:
$result = array_map(function ($i) {
unset($i['customer_name'], $i['random_info']);
return $i;
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
More about array_map
Or you also can select the keys you want:
$result = array_map(function ($i) {
return ['Title' => $i['Title'], 'customer_id' => $i['customer_id']];
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
About your code and question:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
There's no reason to use a count and a for loop, use foreach.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
doesn't make sense, what are these curly brackets? You should write it like this if you want to be understood:
array(
[0] => array(
"Title" => "fakeTitle0",
"customer_id" => "fakeCustomerId0"
),
[1] => array(
"Title" => "fakeTitle1",
"customer_id" => "fakeCustomerId1"
)
);

You have this initial variable.
$listOrderArray = array(
"ListOrdersResult" => array(
"Orders" => array(
"Order" => array(
0 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
1 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
)
)
)
);
The only thing you should do is to remove the inner array from the three outer arrays.
Here is the solution:
$orders = $listOrderArray['ListOrdersResult']['Orders']['Order'];

Related

Assign values in array based on array keys

How to modify an array based on the value as key?
array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220825,
"totals" => 5614
)
);
I tried the following but it's not working:
foreach($cutoffs as $catoff) {
$ii = 0;
$sums[$ii][$catoff] = array_filter($array, function($val){
return $val['cutoff'] === $catoff ? $val['totals'] : $val;
});
$ii++;
}
My desired array:
array(
'20221025' => array(
12345,
12343,
24442
),
'20221110' => array(
3443,
744334
)
)
I'm stuck here for hours ... Please help
IF the "name" is irrelevant, I think also the previous answer should be fine.
If this code does "not work", then your explanation might be wrong, so you need to either explain better, or give us more examples - please mind that in your example the input and output are very different - the input you gave does not match your ouput.
My code is:
$a = array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 1234
)
);
print_r($a);
echo "\n================================\n\n";
$newArr = [];
foreach ($a as $k => $vArr) {
// maybe some validation would be useful here, check if they keys exist
$newArr[$vArr['cutoff']][] = $vArr['totals'];
}
print_r($newArr);
function changeArr($data){
$new = [];
foreach ($data as $v){
$new[$v['cutoff']][] = $v['totals'];
}
return $new;
}

Regroup multidimensional array to reverse presentation of many-to-many relationship

I need to perform iterated explosions on values in one column of my two dimensional array, then re-group the data to flip the relational presentation from "tag name -> video id" to "video id -> tag name".
Here is my input array:
$allTags = [
[
"name" => "TAG-ONE",
"video" => "64070,64076,64110,64111",
],
[
"name" => "TAG-TWO",
"video" => "64070,64076,64110,64111",
],
[
"name" => "TAG-THREE",
"video" => "64111",
]
];
I want to isolate unique video ids and consolidate all tag names (as comma-separayed values) that relate to each video id.
Expected output:
$allTagsResult = [
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64070",
],
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64076",
],
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64110",
],
[
"name" => "TAG-ONE,TAG-TWO,TAG-THREE",
"video" => "64111",
],
];
Somehow I did it by checking the value using nested loops but I wish to know if you guys can suggest any shortest method to get the expected output.
If you want to completely remove foreach() loops, then using array_map(), array_walk_recursive(), array_fill_keys() etc. can do the job. Although I think that a more straightforward answer using foreach() would probably be faster, but anyway...
$out1 = array_map(function ($data) {
return array_fill_keys(explode(",", $data['video']), $data['name']); },
$allTags);
$out2 = [];
array_walk_recursive( $out1, function ( $data, $key ) use (&$out2) {
if ( isset($out2[$key])) {
$out2[$key]['name'] .= ",".$data;
}
else {
$out2[$key] = [ 'name' => $data, 'video' => $key ];
}
} );
print_r($out2);
will give...
Array
(
[64070] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64070
)
[64076] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64076
)
[64110] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64110
)
[64111] => Array
(
[name] => TAG-ONE,TAG-TWO,TAG-THREE
[video] => 64111
)
)
if you want to remove the keys, then
print_r(array_values($out2));
The code could be compressed by piling all of the code onto single lines, but readability is more useful sometimes.
Another method if you don't like looping:
$video_ids = array_flip(array_unique(explode(",",implode(",",array_column($allTags,'video')))));
$result = array_map(function($id){
return ['name' => '','video' => $id];
},array_flip($video_ids));
array_walk($allTags,function($tag_data) use (&$result,&$video_ids){
$ids = explode(",",$tag_data['video']);
foreach($ids as $id) $result[$video_ids[$id]]['name'] = empty($result[$video_ids[$id]]['name']) ? $tag_data['name'] : $result[$video_ids[$id]]['name'] . "," . $tag_data['name'];
});
Demo: https://3v4l.org/vlIks
Below is one way of doing it.
$allTags = [
'0' => [
"name" => "TAG-ONE",
"video" => "64070,64076,64110,64111",
],
'1' => [
"name" => "TAG-TWO",
"video" => "64070,64076,64110,64111",
],
'2' => [
"name" => "TAG-THREE",
"video" => "64111",
]
];
$allTagsResult = array();
$format = array();
foreach( $allTags as $a ) {
$name = $a['name'];
$videos = explode(',', $a['video']);
foreach( $videos as $v ) {
if( !isset( $format[$v]) ) {
$format[$v] = array();
}
$format[$v][] = $name;
}
}
foreach( $format as $video => $names) {
$allTagsResult[] = array('name' => implode(',', $names), 'video' => $video);
}
echo '<pre>';
print_r($allTagsResult);
die;
You can check Demo
I am typically in favor of functional style coding, but for this task I feel it only serves to make the script harder to read and maintain.
Use nested loops and explode the video strings, then group by those video ids and concatenate name strings within each group. When finished iterating, re-index the array.
Code: (Demo)
$result = [];
foreach ($allTags as $tags) {
foreach (explode(',', $tags['video']) as $id) {
if (!isset($result[$id])) {
$result[$id] = ['video' => $id, 'name' => $tags['name']];
} else {
$result[$id]['name'] .= ",{$tags['name']}";
}
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'video' => '64070',
'name' => 'TAG-ONE,TAG-TWO',
),
1 =>
array (
'video' => '64076',
'name' => 'TAG-ONE,TAG-TWO',
),
2 =>
array (
'video' => '64110',
'name' => 'TAG-ONE,TAG-TWO',
),
3 =>
array (
'video' => '64111',
'name' => 'TAG-ONE,TAG-TWO,TAG-THREE',
),
)

Switch between array entries

I am writing an application which interfaces with an external API. We have five API clients (in order to process more requests - which is allowed under the API T&C) which are stored in an array. We have another array of objects which we perform an action on using foreach.
For example:
$clients = array(
array(
"key" => "somekey",
"secret" => "somesecret"
),
array(
"key" => "somekey",
"secret" => "somesecret"
),
array(
"key" => "somekey",
"secret" => "somesecret"
)
);
Next we have an array of objects to be processed:
$objects = array(
array(
"info" => "someinfo",
"url" => "someurl",
"id" => 1234,
"more" => "more"
),
array(
"info" => "someinfo",
"url" => "someurl",
"id" => 1234,
"more" => "more"
),
array(
"info" => "someinfo",
"url" => "someurl",
"id" => 1234,
"more" => "more"
)
);
So to process them with one API key we would do something like:
foreach($objects as $object){
$class->setAPIKey($clients[0]);
$result = $class->process($object);
}
In order to process them with multiple keys we have tried this:
$key = 0;
foreach($objects as $object){
$class->setAPIKey($clients[$key]);
$result = $class->process($object);
if($key + 1 == sizeof($clients)){
$key = 0;
} else {
$key++;
}
}
This works, but seems a little inefficient. Is there a quicker/smaller way to do the same thing?
You can try it like this:
foreach($objects as $key => $object){
$class->setAPIKey($clients[$key]);
$result = $class->process($object);
}

Filter multidimensional array by lowest price

I'm working with an array that I'd like to filter so it only contains the lowest prices per key. So 50 would only have one unit, same with 100, and that unit would be the lowest price.
Here's an example of what I'm working with:
$units = [
50 => [
41788 => ['StdRate' => 231.0000, 'UnitName' => "NN23"],
46238 => ['StdRate' => 303.0000, 'UnitName' => "1038"],
46207 => ['StdRate' => 303.0000, 'UnitName' => "1007"]
],
100 => [
41570 => ['StdRate' => 299.0000, 'UnitName' => "HH18"],
46214 => ['StdRate' => 388.0000, 'UnitName' => "1014"]
]
];
I wanted to avoid doing this with a complicated foreach loop, so I thought an array_filter would be nice, but having a hard time wrapping my head around it. Or would a foreach be best?
$filtered = array_filter($units, function($a) {
});
Expected Output:
[
50 => [
41788 => ['StdRate' => 231.0000, 'UnitName' => "NN23"]
],
100 => [
41570 => ['StdRate' => 299.0000, 'UnitName' => "HH18"]
]
];
Here is a function that will go through your multi-dimensional array and grab the lowest units. It will retain the key of the big array (50, 100) and the key of the unit it grabbed (41788, 41570). It will not retain multiple values of the same low rate. In those cases it will return the first of the lowest value it found. Might not be exactly what you want, but it should be a good start and you can always modify it later. It uses a nested foreach to get its work done.
Hope this help you out!
function findLows($big) {
$lowUnits = array();
foreach($big as $id => $array) {
$low = false;
$prev = false;
foreach($array as $k => $a) {
if(!$low) {
$low = $k;
$prev = $a['StdRate'];
} else {
if($a['StdRate'] < $prev) {
$prev = $a['StdRate'];
$low = $k;
}
}
}
$lowUnits[$id] = array( $low => $array[$low]);
}
return $lowUnits;
}
$bigArray = array();
$bigArray[50][41788] = array('StdRate' => 231.0000, 'UnitName' => "NN23");
$bigArray[50][46238] = array('StdRate' => 303.0000, 'UnitName' => "1038");
$bigArray[50][46207] = array('StdRate' => 303.0000, 'UnitName' => "1007");
$bigArray[100][41570] = array('StdRate' => 299.0000, 'UnitName' => "HH18");
$bigArray[100][46214] = array('StdRate' => 388.0000, 'UnitName' => "1014");
$filtered = findLows($bigArray);
var_dump($filtered);
Will produce:
array(2) {
[50]=>
array(1) {
[41788]=>
array(2) {
["StdRate"]=>
float(231)
["UnitName"]=>
string(4) "NN23"
}
}
[100]=>
array(1) {
[41570]=>
array(2) {
["StdRate"]=>
float(299)
["UnitName"]=>
string(4) "HH18"
}
}
}
For an array with 1 fewer levels of depth, you could have directly iterated the data with array_filter(). Because you want to filter each set of data relating to first level entries, you just need to nest the array_filter() inside of array_map() (for a functional-style script).
I am going to isolate the StdRate values in each set and determine the lowest value by calling min() on the temporary array generated by array_column().
To pass the $min value into the filter's scope, use use().
This snippet will potentially return multiple deep subarrays for a respective set of data IF there is a tie among the lowest values in the set.
Code: (Demo)
$units = [
50 => [
41788 => ['StdRate' => 231.0000, 'UnitName' => "NN23"],
46238 => ['StdRate' => 303.0000, 'UnitName' => "1038"],
46207 => ['StdRate' => 303.0000, 'UnitName' => "1007"]
],
100 => [
41570 => ['StdRate' => 299.0000, 'UnitName' => "HH18"],
46214 => ['StdRate' => 388.0000, 'UnitName' => "1014"]
]
];
var_export(
array_map(
function($unit) {
$min = min(array_column($unit, 'StdRate'));
return array_filter(
$unit,
function($row) use ($min) {
return $row['StdRate'] == $min;
}
);
},
$units
)
);
Output:
array (
50 =>
array (
41788 =>
array (
'StdRate' => 231.0,
'UnitName' => 'NN23',
),
),
100 =>
array (
41570 =>
array (
'StdRate' => 299.0,
'UnitName' => 'HH18',
),
),
)

Using foreach and nested array to insert rows in MySql with PHP

I've written the follow code to try and insert data into a table on the database. However it's just inserting letters. I'm not sure what I'm doing wrong.
$media_items = array(
array (
"media_name" => "Facebook",
"link_url" => "http://www.facebook.com/insightdezign",
"icon" => "facebook.png",
"size" => "48",
"order" => "0"
),
array (
"media_name" => "Twitter",
"link_url" => "http://www.twitter.com/insightdezign",
"icon" => "twitter.png",
"size" => "48",
"order" => "1"
)
);
foreach ($media_items as $media_item) {
if (is_array($media_item)){
foreach ($media_item as $item) {
$rows_affected = $wpdb->insert( $ffui_items, array( 'media_name' => $item['media_name'], 'link_url' => $item['link_url'], 'icon' => $item['icon'], 'size' => $item['size'], 'order' => $item['order'] ) );
}
}
}
Inside your nested foreach loop, you will be looping over strings, not arrays. As a result of type juggling, the indexes will be evaluated to 0. Since PHP also accepts $foo['bar'] syntax on strings, it will just return the first letter.
You can simply remove the nested foreach loop and do it as follows:
foreach ($media_items as $media_item)
{
if (is_array($media_item))
{
$rows_affected = $wpdb->insert( $ffui_items,
array(
'media_name' => $media_item['media_name'],
'link_url' => $media_item['link_url'],
'icon' => $media_item['icon'],
'size' => $media_item['size'],
'order' => $media_item['order']
) ;
}
}

Categories