Json split print_r to foreach - php

I have the following code
$List2 = json_decode(file_get_contents("https://___URL____&format=json"),true);
the following works perfectly
echo '<pre>';print_r($List2);echo '</pre>';
and produces e.g.
Array
(
[0] => Array
(
[uid] => 123456
[name] => John Williams
[pic_square] => http://nc4/565228_799523_q.jpg
[birthday_date] => 07/31/1987
)
[1] => Array
(
[uid] => 123789
[name] => Jane Thompson
[pic_square] => http://profile.ak.fbcdn.net/785505233_1702140670_q.jpg
[birthday_date] => 07/31/1983
)
[2] => Array
(
[uid] => 456789
[name] => John Gaffney
[pic_square] => http://profet/hprofile-ak-snc4/3717297628_q.jpg
[birthday_date] => 07/31/1965
)
[3] => Array
(
[uid] => 987654
[name] => Johnny Illand
[pic_square] => http://c4/41766_14329_q.jpg
[birthday_date] => 07/31/1958
)
I want to run a foreach to print the result somewhat neater obviously, so i'm trying the following:
$data = $List2['data'] ;
foreach ($data as $nr => $friends){
echo $friends[name].' - ';
}
But I get
Warning: Invalid argument supplied for foreach()
I'm stumped and it's probably something easy!

Try with:
foreach ($List2 as $element)
echo $element[name].' - ';

In this example the 'data' key does not exists
$data = $List2;

Related

How to combine array value with same key?

So i have this array that i get from query. The array look like this when i print_r
Array
(
[0] => Array
(
[Name] => NAME 1
[Last] => LastValue1
[Bid] =>
[Ask] =>
)
[1] => Array
(
[Name] => NAME 1
[Last] =>
[Bid] => BidValue1
[Ask] =>
)
[2] => Array
(
[Name] => Name 2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] =>
)
[3] => Array
(
[Name] => NAME 1
[Last] =>
[Bid] =>
[Ask] => AskValue1
)
[4] => Array
(
[Name] =>Name 2
[Last] =>
[Bid] =>
[Ask] => AskValue2
)
)
and i want to achieve array looks like this
Array
(
[0] => Array
(
[Name] => NAME 1
[Last] => LastValue1
[Bid] => BidValue1
[Ask] => AskValue1
)
[2] => Array
(
[Name] => Name 2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] => AskValue2
)
)
I try this way (get it from google)
$result = array();
foreach ($newArray as $element) {
$result[$element['Name']][] = $element;
}
echo "<pre>";print_r($result);
But it is not showing the result that i want. How can i achieve it ?
thanks in advance and sorry for my english
You can use below snippet for the same,
$result = [];
foreach ($newArray as $element) {
foreach ($element as $key => $value) {
// checking if value for key is already added to result array
if ((!empty($result[$element['Name']]) && !array_key_exists($key, $result[$element['Name']])) || empty($result[$element['Name']])) {
if (!empty($value)) { // checking if value not empty
$result[$element['Name']] = ($result[$element['Name']] ?? []);
// merge it to group wise name result array
$result[$element['Name']] = array_merge($result[$element['Name']], [$key => $value]);
}
}
}
}
array_merge — Merge one or more arrays
array_key_exists — Checks if the given key or index exists in the array
Demo
Output:-
Array
(
[0] => Array
(
[Name] => NAME1
[Last] => LastValue1
[Bid] => BidValue1
[Ask] => AskValue1
)
[1] => Array
(
[Name] => Name2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] => AskValue2
)
)
Here is the shortest and simple solution by using foreach with array_filter
foreach($a as &$v){
$v = array_filter($v);
isset($r[$v['Name']]) ? ($r[$v['Name']] += $v) : ($r[$v['Name']] = $v);
}
You can use array_values to re arrange the order of array.
Working example : https://3v4l.org/XeQHa

Set some array value as key of an array

I have tried this line of code to display an array:
foreach($users_array as $value){
echo "<pre>";
print_r($value);
}
Which display this kind of array.
Array
(
[auto_id] => 45
[id] => 20151116
[name] => Peter 2
[department] =>
[position] =>
[rate] => 300
[date_added] => 2017-07-26 09:31:44
)
Array
(
[auto_id] => 80
[id] => 20160410
[name] => John 2
[department] =>
[position] =>
[rate] => 400
[date_added] => 2017-07-26 09:31:48
)
Now what I wanted to do is to make the id of employee to be the key of an array and make them as one multi-dimensional array.
Example output should be like this:
Array
(
[20151116] => Array
(
[auto_id] => 45
[id] => 20151116
[name] => Peter 2
[department] =>
[position] =>
[rate] => 300
[date_added] => 2017-07-26 09:31:44
)
[20160410] => Array
(
[auto_id] => 80
[id] => 20160410
[name] => John 2
[department] =>
[position] =>
[rate] => 400
[date_added] => 2017-07-26 09:31:48
)
)
Any help is appreciated. Thank you.
It's probably easiest to make a new array the you output directly, and loop over the existing array, setting the id as an index of the new array:
<?php
$newArray = array();
foreach($users_array as $value) {
$newArray[$value["id"]] = $value;
print_r($newArray);
}
Hope this helps! :)
Here you need to change
$final = array();
foreach($users_array as $value){
$final[$value["id"]] = $value;
}
echo "<pre>";
print_r($final);
Use the function array_column() and array_combine(), like this:
$employee_id = array_column($users_array,'id');
$users_array = array_combine($employee_id,$users_array);

Merging two array elements in one

How can I do to merge "artist" value with "title" value in one value?. I'm using PHP 5.2.4 if that helps.
I have this array
Array
(
[0] => Array
(
[artist] => Narcosis
[title] => Destruir
[duration] => 137
[date] => 1370807642
[genre_id] => 18
)
[1] => Array
(
[artist] => Ricardo Palma Fanjul
[title] => Mutant
[duration] => 347
[date] => 1448227909
[genre_id] => 18
)
)
The expected output would be like this, just show element "title" with twice values:
Array
(
[0] => Array
(
[title] => Narcosis - Destruir
[duration] => 137
[date] => 1370807642
[genre_id] => 18
)
[1] => Array
(
[title] => Ricardo Palma Fanjul - Mutant
[duration] => 347
[date] => 1448227909
[genre_id] => 18
)
)
Try this:
foreach ($mainArr as $index=>$subArr) {
$subArr['title'] = $subArr['artist'].' - '.$subArr['title'];
unset($subArr['artist']);
$mainArr[$index] = $subArr;
}
mainArr is the array declared above.
p.s. I have not tested this code yet
Try this:
$new = array_map(function($v) {
$v['title'] = $v['artist'].' - '.$v['title'];
unset($v['artist']);
return $v;
}, $arr);
OR
foreach ($arr as &$a) {
$a['title'] = $a['artist'].' - '.$a['title'];
unset($a['artist']);
}

How to parse array elements?

I tried to parse a string array using the code below but the required data never printed! could any one tell me how to fix it ?Thanks
$data Array structure :
Array
(
[js] => Array
(
[total_items] => 20
[max_page_items] => 2
[selected_item] => 0
[cur_page] => 0
[data] => Array
(
[0] => Array
(
[tmp] => 1
[name] => mango
[abc] => abcd4 http://mysite/items/1234
[number] => 1123
[itemCategory_title] => fruits
[logo] => 2123.png
[itemCategory_id] => 90
)
[1] => Array
(
[tmp] => 0
[name] => cherry
[abc] => abcd4 http://mysite/items/1235
[number] => 1124
[itemCategory_title] => fruits
[logo] => 2124.png
[itemCategory_id] =>
)
)
)
[text] => no error
)
php code:
<?
$code2 = stripslashes($_POST['outputtext']);
$data = json_decode($code2);
foreach( $data as $item ) {
echo $item['tmp'];
echo $item['name'];
echo $item['abc'];
echo $item['number'];
echo $item['itemCategory_title'];
echo $item['log'];
echo $item['itemCategory_id'];
}
?>
It should be:
foreach ($data['js']['data'] AS $item)
because the array is nested several levels down in $data.
Note that you need to call json_decode($code2, true) to get an associative array like that. By default, it returns an object, not an array, so you would do:
foreach ($data->js->data as $item) {
echo $item->tmp;
echo $item->name;
...
}

Merging two array elements into one array element in PHP

I want to merge two arrays into one array as follows,
Array1:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
)
)
Array2:
Array
(
[0] => Array
(
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
Expected array result is:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
How to merge these array elements into one array element ?
foreach ($origArray as $key => &$subArray)
$subArray += $arrayToBeAdded[$key];
Where $origArray is your array which is to be merged into and $arrayToBeAdded the array you merge into.
User array_merge_recursive():
$final = array_merge_recursive($array1, $array2);
Try this little known overload of the + operator for arrays:
$result = $array1[0] + $array2[0]
Use function array_merge($array1[0], $array2[0]) . Following is the example for the same
$array1 = array(0=>array('1'=>1,'2'=>2,'3'=>3));
$array2 = array(0=>array('4'=>4,'5'=>5,'6'=>6));
$result[0] = array_merge($array1[0],$array2[0]);
echo '<pre>';
print_r($result);
Since you have unique keys, you could use something as simple as the + operator (union)...
For example:
$arr1 = [1=>'testing',2=>'stack',3=>'overflow'];
$arr2 = [4=>'something',5=>'else',6=>'here'];
$arr3 = $arr1 + $arr2;
print_r($arr3);
Results:
Array ( [1] => testing [2] => stack [3] => overflow [4] => something [5] => else [6] => here )
For this php has multiple functions. You can use $arrays = array_combine($array1, $array2);.
PHP.net - array_combine
Hope it helped!

Categories