How to fetch the values from array of array - php

I need to fetch Title summary cover values from this code. Please help me out in fetching the values of rawdata and I need to loop them.
Can someone pls help me out
Array
(
[rawData] => Array
(
[csrf_hash_name] => 57b9481862e81cf2ebe9ed4e962355db
[title] => gfgf
[summary] => hfdhfhfdhdf
[cover] => clockface - 2.png
[id] => Array
(
[0] =>
[1] =>
)
)

just call it by its key:
$arr = Array
(
'rawData' => Array
(
'csrf_hash_name' => 57b9481862e81cf2ebe9ed4e962355db,
'title' => gfgf,
'summary' => hfdhfhfdhdf,
'cover' => clockface - 2.png,
'id' => Array
(
0 => '',
1 => ''
)
);
and then use
$title = $arr['rawData']['title'];
$summary = $arr['rawData']['summary'];

Try this code below
<?php
$array = array(
"rawData" => array(
"csrf_hash_name" => "57b9481862e81cf2ebe9ed4e962355db",
"title" => "gfgf",
"summary" => "hfdhfhfdhdf",
"cover" => "clockface - 2.png",
"id" => array(
0 => "",
1 => ""
)
)
);
foreach($array["rawData"] as $key => $arr) {
$fetchValue = array('title', 'summary', 'cover');
if(in_array($key, $fetchValue)) {
$$key = $arr;
}
}
echo $title;
echo $summary;
echo $cover;
?>
Cheers!

<?php
$array = array(
"rawData" => array(
"csrf_hash_name" => "57b9481862e81cf2ebe9ed4e962355db",
"title" => "gfgf",
"summary" => "hfdhfhfdhdf",
"cover" => "clockface - 2.png",
"id" => array(
0 => "",
1 => ""
)
)
);
$arr2 = array();
foreach($array["rawData"] as $key => $arr) {
$fetchValue = array('title', 'summary', 'cover');
if (in_array($key, $fetchValue)) {
$arr2[$key] = $arr;
}
}
extract($arr2);
echo $title;
echo '<br/>';
echo $summary;
echo '<br/>';
echo $cover;
?>

Related

Compare and combine multidimensional array then sort descending PHP

I have 2 multi arrays, profiles and encoded arrays like this
$profiles = array(
array(
'user_id' => 'fcc3d884-fbef-438a-9c86-0ad52c9b1223',
'first_name' => 'Narñia',
'middle_name' => 'Ñ',
'last_name' => 'Cruz',
'ext' => ''
),
array(
'user_id' => '0d31557d-1e9f-4db3-ac0d-72e1709fe89c',
'first_name' => 'Randy',
'middle_name' => 'O',
'last_name' => 'Rocker',
'ext' => ''
),
array(
'user_id' => '0f93f169-cf56-49df-a76b-7596446104c6',
'first_name' => 'Qwerty',
'middle_name' => 'K',
'last_name' => 'Asdfg',
'ext' => ''
),
array(
'user_id' => '23b1f4a2-034c-43b4-96b7-3191d78cead1',
'first_name' => 'Johny',
'middle_name' => 'L',
'last_name' => 'Walker',
'ext' => ''
)
);
$encoded = array(
array(
'encoder_id' => '0d31557d-1e9f-4db3-ac0d-72e1709fe89c',
'fullname' => 'Randy O. Rocker',
'encoded' => 10,
),
array(
'encoder_id' => '23b1f4a2-034c-43b4-96b7-3191d78cead1',
'fullname' => 'John L. Walker',
'encoded' => 20,
)
);
Now i want to get some data from $profiles then combine to $encoded array when user_id and encoder_id is match, i have this code but it seems wrong it only gets "John L. Waler" data. here's my code.
$data = [];
foreach ($profiles as $key => $val) {
$user_id = $val['user_id'];
foreach($encoded as $k => $v){
$ext_name = ($val['ext'] == '') ? '' : $val['ext'];
$fullname = $val['first_name'].' '.substr($val['middle_name'], 0, 1).'. '.$val['last_name'].' '.$ext_name;
$data[$key] = array(
'id' => ($v['encoder_id'] == $user_id) ? $v['encoder_id'] : $user_id,
'fullname' => ($v['encoder_id'] == $user_id) ? $v['fullname'] : $fullname,
'encoded' => ($v['encoder_id'] == $user_id) ? $v['encoded'] : 0
);
}
}
echo '<pre>';
print_r($data);
echo '</pre>';
here's the result
Array
(
[0] => Array
(
[id] => fcc3d884-fbef-438a-9c86-0ad52c9b1223
[fullname] => Narñia �. Cruz
[encoded] => 0
)
[1] => Array
(
[id] => 0d31557d-1e9f-4db3-ac0d-72e1709fe89c
[fullname] => Randy O. Rocker
[encoded] => 0 //this should be 10
)
[2] => Array
(
[id] => 0f93f169-cf56-49df-a76b-7596446104c6
[fullname] => Qwerty K. Asdfg
[encoded] => 0
)
[3] => Array
(
[id] => 23b1f4a2-034c-43b4-96b7-3191d78cead1
[fullname] => John L. Walker
[encoded] => 20
)
)
Also after combining them to a new array. i want to sort the new array by "encoded" attribute descending.
Thank you for understanding
You can make your life easier by re-indexing the $encoded array by the encoder_id values using array_column; then you don't have to search the array each time to look for a user_id value, you can just use isset. Once you've extracted your data, you can use usort to sort by the encoded values:
$encoded_ids = array_column($encoded, null, 'encoder_id');
$data = array();
foreach ($profiles as $profile) {
$user_id = $profile['user_id'];
if (isset($encoded_ids[$user_id])) {
$data[] = array('id' => $user_id,
'fullname' => $encoded_ids[$user_id]['fullname'],
'encoded' => $encoded_ids[$user_id]['encoded']
);
}
else {
$data[] = array('id' => $user_id,
'fullname' => "${profile['first_name']} ${profile['middle_name']} ${profile['last_name']}",
'encoded' => 0
);
}
}
usort($data, function ($a, $b) { return $b['encoded'] - $a['encoded'];});
print_r($data);
Output:
Array
(
[0] => Array
(
[id] => 23b1f4a2-034c-43b4-96b7-3191d78cead1
[fullname] => John L. Walker
[encoded] => 20
)
[1] => Array
(
[id] => 0d31557d-1e9f-4db3-ac0d-72e1709fe89c
[fullname] => Randy O. Rocker
[encoded] => 10
)
[2] => Array
(
[id] => fcc3d884-fbef-438a-9c86-0ad52c9b1223
[fullname] => Narñia Ñ Cruz
[encoded] => 0
)
[3] => Array
(
[id] => 0f93f169-cf56-49df-a76b-7596446104c6
[fullname] => Qwerty K Asdfg
[encoded] => 0
)
)
Demo on 3v4l.org
An alternative to Nick's version, using array_reduce:
$encodedByEncoderId = array_column($encoded, null, 'encoder_id');
$combined = array_reduce($profiles, function (array $combined, array $profile) use ($encodedByEncoderId): array {
$combined[] = [
'id' => $profile['user_id'],
'fullname' => $encodedByEncoderId[$profile['user_id']]['fullname']
?? "{$profile['first_name']} {$profile['middle_name']}. {$profile['last_name']}",
'encoded' => $encodedByEncoderId[$profile['user_id']]['encoded']
?? 0
];
return $combined;
}, []);
Demo: https://3v4l.org/kKBru
Try this!
$data = [];
foreach ($profiles as $key => $val) {
$user_id = $val['user_id'];
$is_matched = 0;
$encoded_data = [];
foreach($encoded as $k => $v){
if ($user_id == $v['encoder_id']) {
$is_matched = 1;
$encoded_data = $v;
}
}
$ext_name = ($val['ext'] == '') ? '' : $val['ext'];
$fullname = $val['first_name'].' '.substr($val['middle_name'], 0, 1).'. '.$val['last_name'].' '.$ext_name;
$data[$key] = array(
'id' => ($is_matched == 1) ? $encoded_data['encoder_id'] : $user_id,
'fullname' => ($is_matched == 1) ? $encoded_data['fullname'] : $fullname,
'encoded' => ($is_matched == 1) ? $encoded_data['encoded'] : 0
);
}

Looping and combine multiple array to one

I have an array looks like this:
Array
(
[0] => Array
(
[name] => color
[value] => red
)
[1] => Array
(
[name] => shape
[value] => square
)
[2] => Array
(
[name] => price
[value] => $15
)
)
I want to have a result like this:
$myArr = array (
'color' => 'red',
'shape' => 'square',
'price' => '$15'
)
I have tried to loop but can not get it to work.
foreach($myArr as $id => $values){
foreach ($values as $key => $value) {
if($key == 'name') {
//add to array key
} else {
//add to that array key value
}
}
}
hope you guys can help me with solution.
You can use array_column and array_combine
$arr = array(
array("name" => 'color',"value" => 'red'),
array("name" => 'shape',"value" => 'square'),
array("name" => 'price',"value" => '$15')
);
$newArr = array_combine(array_column($arr,'name'),array_column($arr,'value'));
echo "<pre>";
print_r( $newArr );
echo "</pre>";
This will result to:
Array
(
[color] => red
[shape] => square
[price] => $15
)
Doc: array_column, array_combine
$a = [
0 => [
"name" => "color",
"value" => "red",
],
1 => [
"name" => "shape",
"value" => "square",
],
2 => [
"name" => "price",
"value" => "$15",
]
];
$b = [];
foreach($a as $v)
{
$b[$v["name"]] = $v["value"];
}
var_dump($b);
result
array(3) {
["color"]=>
string(3) "red"
["shape"]=>
string(6) "square"
["price"]=>
string(3) "$15"
}
$arr = array
(
0 => array
(
'name' => 'color',
'value' => 'red'
),
1 => array
(
'name' => 'shape',
'value' => 'square'
),
2 => array
(
'name' => 'price',
'value' => '$15'
)
);
$final_array =[];
foreach($arr as $key=> $val){
$final_array[$val['name']] = $val['value'];
}
echo "<pre>"; print_r($final_array);

Search in multidimensional array by key and return the sub array

I have multidimensional array and i want to extract a sub array by its key.
Example array:
[libra] => Array
(
[schema_id] => LibraModel
[libra_guid] => a2d02184-5a83-0f1b-673d-7f215fe6ba02
[is_test_client] =>
[is_web_bot] =>
[tag_collection] => Array
(
[schema_id] => TestGroupAssignmentModel
[tags_by_test] => Array
(
[checked] => Array
(
[first] => Tester
[second] => de11e041-1083-44bb-96dc-134fa099f737
[control] => false
)
[optionSelected] => Array
(
[schema_id] => TestGroupAssignmentModel
[test_group_guid] => 6a28c568-a416-4d3a-a993-4eb7f6ce19d3
[control] =>
[test_name_hash] => ecdd6bf92e27aa10ca5e3acbe385fb6b
[fully_qualified_hash] => 9e97e3244516f219887294435975df22
[do_not_track] =>
)
)
)
)
From this array i want to get only the optionSelected, and keep it's structure.
Best function i did so far is this:
$multi_array is the array displayed on above,
$array_key is string 'optionSelected'
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($multi_array));
foreach($iterator as $key => $value) {
if($array_key == $key){
echo $key;
}
}
This should get the job done:
<?php
$array = [
'test' => 'value',
'level_one' => [
'level_two' => [
'level_three' => [
'replace_this_array' => [
'special_key' => 'replacement_value',
'key_one' => 'testing',
'key_two' => 'value',
'four' => 'another value'
]
],
'ordinary_key' => 'value'
]
]
];
$recursiveIterator = new \RecursiveIteratorIterator(
new \RecursiveArrayIterator($array),
\RecursiveIteratorIterator::SELF_FIRST
);
$extractKey = "level_three";
$result = [];
foreach ($recursiveIterator as $key => $value) {
if ($key === $extractKey) {
$result = $value;
}
}
var_dump($result);
Thanks to the \RecursiveIteratorIterator::SELF_FIRST the $value will always contain the whole sub array.

Grouping in array

I have following array..I am trying to group this.
Array
(
[0] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I want to group this into
Array
(
[0] => Array
(
[VitalInfo]=>array(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price]=>array(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I tried but it doesn't happen as I want ...any help would be great...Thanx in advance..
try this,
CODE :
foreach($old_array as $key_old => $val_old)
{
foreach($val_old as $key => $val)
{
if(in_array($key, $VitalInfo_array))
{
$new_array[$key_old]['VitalInfo'][$key] = $val;
}
else
{
$new_array[$key_old]['Price'][$key] = $val;
}
}
}
OUTPUT :
Array
(
[0] => Array
(
[VitalInfo] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price] => Array
(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
)
DEMO
i hope it will be helpful.
Simply loop through your array and customize a new array accordingly.
Assuming $array is the original array, and $result is the customized array, try this:
foreach ($array as $k => $arr) {
$result[$k]['VitalInfo'] = array(
'Title' => $arr['Title'],
'ean' => $arr['ean'],
'upc' => $arr['upc'],
'ProductImageName' => $arr['ProductImageName'],
'CdnUri' => $arr['CdnUri'],
'ASIN' => $arr['ASIN']
);
$result[$k]['Price'] = array(
'ListPrice' => $arr['ListPrice'],
'Status' => $arr['Status'],
'ActualPrice' => $arr['ActualPrice'],
'ProductID' => $arr['ProductID']
);
}
Input : $info // Your Original Array
Ouput : $finalArr // Your Required Array
$vitalInfo = array ('Title','ean','upc','ProductImageName','CdnUri','ASIN');
$price = array ('ListPrice','Status','ActualPrice','ProductId');
$finalArr = array();
foreach ($info as $arr) {
$result = array();
foreach($arr as $k => $v){
if(in_array($k,$vitalInfo))
$result['VitalInfo'][$k] = $v;
else if(in_array($k,$price))
$result['Price'][$k] = $v;
}
$finalArr[] = $result;
}
If you are grouping this in php, have a look at these answers.
Or just copy this:
$input = [0 => [
'Title' => 'HoMedics MAN-300',
'ean' => 31262006288,
'upc' => 31262006288,
'ProductImageName' => '',
'CdnUri' => '',
'ASIN' => 'B000050FEU',
'ListPrice' => 129.99,
'Status' => 2,
'ActualPrice' => 129.99,
'ProductID' => 5286728
]];
foreach ($input as $in){
$out['VitalInfo'] = [];
$out['Price'] = [];
foreach ($in as $key => $i){
if (in_array($key, ['Title', 'ean', 'upc', 'ProductImageName', 'CdnUri', 'Asin'])){
$out['VitalInfo'][] = [$key => $i];
} else {
$out['Price'][] = [$key => $i];
}
}
$output[]=$out;
}
echo '<pre>';
var_dump($output);

Re-arrange array (move from key to value) and organize order

I have this array:
Array
(
[LLLLLLL:] => Array
(
[ brand1:] => Array
(
[people: (100%)] => Array
(
)
[countries: (90%)] => Array
(
)
[yyyy: (80%)] => Array
(
)
[languages: (70%)] => Array
(
)
)
[ brand2:] => Array
(
[people: (60%)] => Array
(
)
[countries: (50%)] => Array
(
)
[yyyy: (40%)] => Array
(
)
[languages: (30%)] => Array
(
)
)
)
)
How can I re-arrange my array in order to have this:
array(
array(
('LLLLLLL') => 'people',
('BRAND1') => '100%',
('BRAND2') => '60%'),
array(
('LLLLLLL') => 'countries',
('BRAND1') => '90%',
('BRAND2') => '50%')
array(
('LLLLLLL') => 'yyyy',
('BRAND1') => '80%',
('BRAND2') => '50%')
array(
('LLLLLLL') => 'languages',
('BRAND1') => '70%',
('BRAND2') => '30%',
I have no idea, how to, for example, move the string after ':' on key to the value and than re-arrange in the different order. How can this be done?
I think this should do it. Please note that it was not tested:
$result = array();
foreach ($initialArray as $lll => $brands) {
$lll = rtrim($lll, ':');
foreach ($brands as $brandName => $brandValues) {
$brandName = strtoupper(preg_replace('/[\s:]/', '', $brandName));
$values = array_keys($brandValues);
foreach ($values as $value) {
preg_match('/([a-z]*): \(([0-9]*%)\)/', $value, $matches);
if (!isset($result[$matches[1]])) {
$result[$matches[1]] = array($lll => $matches[1]);
}
$result[$matches[1]][$brandName] = $matches[2];
}
}
}
You can use regexp + array_map for it.
$datos = Array(
'LLLLLLL:' => Array(
'brand1:' => Array(
'people: (100%)' => Array
(
),
'countries: (90%)' => Array
(
),
'yyyy: (80%)' => Array
(
),
'languages: (70%)' => Array
(
)
),
'brand2:' => Array(
'people: (60%)' => Array
(
),
'countries: (50%)' => Array
(
),
'yyyy: (40%)' => Array
(
),
'languages: (30%)' => Array
(
)
)
)
);
$datos = array_map(function($row) {
$ret = array();
foreach ($row as $key => $items) {
foreach ($items as $dato => $vacio) {
if (preg_match('/([^:]+): \(([^\)]+)\)/i', $dato, $coincidencias)) {
$pos = $coincidencias[1];
if (!isset($ret[$pos]))
$ret[$pos] = array();
$ret[$pos][$key] = $coincidencias[2];
}
}
}
return $ret;
}, $datos);
echo '<pre>' . print_r($datos, true);
Is not completed, but you can go in this way.

Categories